0

XML ドキュメントの次のサンプルがあり、すべての「リンク」要素をドキュメントから切り離す必要があります

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://my.netscape.com/rdf/simple/0.9/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">
<channel>
  <title>Slashdot</title> 
  <link>http://slashdot.org/</link> 
  <description>News for nerds, stuff that matters</description> 
  </channel>
<image>
  <title>Slashdot</title> 
  <url>http://a.fsdn.com/sd/topics/topicslashdot.gif</url> 
  <link>http://slashdot.org/</link> 
  </image>
  <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/xml" href="http://rss.slashdot.org/Slashdot/slashdot/to" /> 
  </rdf:RDF>

それは私が使用しているコードです

while (iterator.hasNext()) {
    Object next = iterator.next();
    Element element = (Element) next; 
    Namespace namespace = element.getNamespace();
    Element link = element.getChild("link",namespace);
    link.detach();
}

属性のない「リンク」要素でうまく機能します

<link>http://slashdot.org/</link>
<link>http://slashdot.org/</link>

しかし、リンクでもある次の子を取得したいが、属性と名前空間が異なる場合、null オブジェクト参照が返されます

<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/xml" href="http://rss.slashdot.org/Slashdot/slashdot/to" /> 

助けてください

どうもありがとうデビッド

4

1 に答える 1

0

名前空間に関係なく、ローカル名が 'link' のすべての要素を削除する場合、最も簡単な解決策は XPath です。この式//*[local-name() = 'link]は、ローカル名が「link」であるドキュメント内のすべての要素ノードを選択します。

    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(...));
    List<Element> result = XPath.selectNodes(doc, "//*[local-name() = 'link']");
    for (Element e : result)
        e.detach();
于 2011-06-06T14:28:01.113 に答える