我正在使用DOM模型来解析XML文件。 我需要从XML文件中删除每个偶数节点(第二,第四,第六...)。 必须使用递归来实现删除。
例如,我有XML:
<PHONEBOOK>
<PERSON>
<NAME>Joe Wang</NAME>
<EMAIL>joe@yourserver.com</EMAIL>
<TELEPHONE>202-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Karol</NAME>
<EMAIL>karol@yourserver.com</EMAIL>
<TELEPHONE>306-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
</PHONEBOOK>
删除后,我想要这样的XML:
<PHONEBOOK>
<PERSON>
<NAME>Joe Wang</NAME>
... 2nd node was removed ...
<TELEPHONE>202-999-9999</TELEPHONE>
... 4th node was removed ...
</PERSON>
... 2nd node was removed ...
</PHONEBOOK>
我已经编写了使用递归访问所有节点的方法,但我现在不知道如何删除每个节点中的每个偶数节点
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(
new File("src/main/resources/inputForDom.xml")));
Node root = doc.getDocumentElement();
doc.normalize();
visit(root);
}
------------
public static void visit(Node node) {
NodeList books = node.getChildNodes();
for (int i = 0; i < books.getLength(); i++) {
Node book = books.item(i);
if (book.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(book.getNodeName());
// Should be something like this for removing node...
//book.getParentNode().removeChild(books.item(?));
}
// recursion
visit(book);
}
}
感谢您的帮助