我想删除包含值#delete
的所有节点,例如在下面的XML中,应删除<id>
和<price>
个节点,因为它们的值包含#delete
< / p>
<root>
<product>
<id>#delete</id>
<name>shirt</name>
<desc>product description</desc>
<price>#delete</price>
</product>
</root>
答案 0 :(得分:0)
如果您的XML示例位于工作目录中名为products.xml
的文件中,则此代码段应该可以工作并将结果打印到控制台。
这是一个例子,让您了解如何使用org.w3c.dom
(如果您的XML结构更深,那么您必须以递归方式读取所有子项)
//load DOM
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document dom = builder.parse(new File("products.xml"));
//get all products
NodeList products = dom.getElementsByTagName("product");
for (int i = 0; i < products.getLength(); i++) {
Node product = products.item(i);
NodeList nodes = product.getChildNodes();
for (int j = 0; j < nodes.getLength(); j++) {
Node node = nodes.item(j);
// check content
if ("#delete".equals(node.getTextContent())) {
product.removeChild(node);
}
}
}
//write to system out
writer = new BufferedWriter(new OutputStreamWriter(System.out));
OutputFormat format = new OutputFormat(Method.XML, encoding, true);
XMLSerializer xml = new XMLSerializer(writer, format);
xml.serialize(dom);