【发布时间】:2016-03-11 06:48:26
【问题描述】:
我有一个非常简单的 xml 文件,我想创建一个简单的函数来从中删除标签。这是我的示例 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>
你能推荐一下吗?
【问题讨论】:
-
因为你删除了频道,你也删除了它的内部子项。因此,为了让孩子将其分配给一个变量,并在删除通道后添加项目的孩子。