如果有一个名为a.xml的XML文件,有没有办法遍历它的DOM树 后购时尚?
我尝试使用GetNextSiblings方法,但它不起作用。有什么想法吗?
这是 XML:
<?xml version="1.0" encoding="UTF-8"?>
<title text="title1">
<comment id="comment1">
<data> abcd </data>
<data> efgh </data>
</comment>
<comment id="comment2">
<data> ijkl </data>
<data> mnop </data>
<data> qrst </data>
</comment>
</title>
这是我的遍历它的代码:
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.SAXException;
public class Newtraverse {
public static Node check(Node node){
Node c=node;
// Node c = null;
if (node!=null)
if (node.hasChildNodes()==true &&node.getNodeName()!=null)
{
node=node.getFirstChild().getNextSibling();
if (node!=null)
{
System.out.println(node);
check(node);
}
if(node==null)
{
c=c.getNextSibling();
check(c);
}
}
return node;
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
File file = new File("d:\\a.xml");
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
Node b=document.getFirstChild();
Node result= check(b);
}
}
这是输出:
[comment: null]
[data: null]
大家可以看到,它只是遍历了两个标签。我该如何解决这个问题?
最佳答案
这是你的检查方法应该是什么样的(虽然我没有运行它......)
public static void check(Node node){
if (node == null || node.getNodeName() == null)
return;
// Do PostOrder on all children
check(node.getFirstChild());
// Now that all children were traversed, process the current node:
System.out.println(node);
// Do PostOrder on following siblings
check(node.getNextSibling();
}
关于java - dom 树的后序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8103618/