Thursday, 31 December 2015

XML : Cannot Trace the Recursive within for Loop

  public class DOMTreeTraversal{        /**       * @param args       * @throws Exception        */      public static void main(String[] args) throws Exception {          // TODO Auto-generated method stub            DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance();          DocumentBuilder docBuilder=docBuilderFactory.newDocumentBuilder();          Document doc=docBuilder.parse(new FileInputStream("myFile.xml"));          Node n=doc.getDocumentElement();            walk(n);        }        private static void walk(Node n)      {          for(Node temp=n.getFirstChild();temp!=null;temp=temp.getNextSibling())          {              if(temp.getNodeType()==Node.ELEMENT_NODE)              System.out.println(temp.getNodeName());              if(temp.getNodeType()==Node.TEXT_NODE)                  System.out.println("Text Node");                walk(temp);          }      }    }  

my xml file is

  <?xml version="1.0" encoding="UTF-8"?>    

<team>
<member>
<name>Smith</name>
<age>40</age>
<gender>male</gender>
</member>
<member>
<name>Rose</name>
<age>30</age>
<gender>female</gender>
</member>
</team>

when running the code the result is

Text Node
member
Text Node
name
Text Node
Text Node
age
Text Node
Text Node
gender
Text Node
Text Node
member
Text Node
name
Text Node
Text Node
age
Text Node
Text Node
gender
Text Node
Text Node
Text Node

I have difficulty in tracing the code: for the first call of walk method : walk(team) temp=textnode and the first recursive call will be walk(text node) and on the stack will be walk(team) for the first recursive call since the is no child node for the text node temp will be null, so the for loop for first recursive call will be end the walk(team) will be restart In that case there is the first child of element is also previous text node. So I cannot continue to trace.

I would like to know that my tracing method is wrong.

No comments:

Post a Comment