If there is an XML file called a.xml, is there any way to traverse its DOM tree in
postorder fashion?
I tried using GetNextSiblings method but it didn’t work. Any idea?
Here is the 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>
And here is my code to traverse it:
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);
}
}
And here is the output:
[comment: null]
[data: null]
As you all can see, it just traverses two tags. How can I fix this?
Here’s how your check method should like (I didn’t run it though…)