1
我有一個非常簡單的xml文件,我想創建一個簡單的函數來從中刪除標記。這裏是我的示例XML文件:使用java刪除xml標記
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channels>
<channel>
<items>
<item>
<title>Java Tutorials></title>
<link>http://www.tutorial-point.com/</link>
</item>
<item>
<title>Java Tutorials></title>
<link>http://www.javatpoint.com/</link>
</item>
</items>
</channel>
</channels>
</rss>
在我的Java程序,只是想調用一個方法來從文件中刪除兩個標籤。我對XML不是很熟悉,但設法創建了一個讀寫器,但現在我無法創建一個從我的文件中刪除項目的方法。
// retrieve the element
Element element = (Element) doc.getElementsByTagName("channels").item(0);
Element element2 = (Element) doc.getElementsByTagName("channel").item(0);
// remove the specific node
element.getParentNode().removeChild(element);
element2.getParentNode().removeChild(element2);
當我在Java中使用上面的代碼,它刪除了所有的標籤,但我期待的結果如下圖所示:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<items>
<item>
<title>Java Tutorials></title>
<link>http://www.tutorial-point.com/</link>
</item>
<item>
<title>Java Tutorials></title>
<link>http://www.javatpoint.com/</link>
</item>
</items>
</rss>
能否請你建議?
由於您刪除了頻道,因此您還要刪除其內部的子項目。所以爲了讓小孩把它分配給一個變量,並在刪除頻道後添加項目的子項。 – sgpalit