title: Efficient way of parsing XML in Java
body: <p>I have to parse an XML file with following structure: </p>
  
  <pre><code>&lt;root&gt;
      &lt;object_1&gt;
          &lt;pro1&gt; abc &lt;/pro1&gt;
          &lt;pro2&gt; pqr &lt;/pro2&gt;
          &lt;pro3&gt; xyz &lt;/pro3&gt;
  
          &lt;children&gt;
              &lt;object_a&gt;
                  &lt;pro1&gt; abc &lt;/pro1&gt;
                  &lt;pro2&gt; pqr &lt;/pro2&gt;
                  &lt;pro3&gt; xyz &lt;/pro3&gt;
  
                  &lt;children&gt;
                      .
                      .
                      .
                  &lt;/children&gt;
              &lt;/object_a&gt;
          &lt;/children&gt;     
      &lt;/object_1&gt;
      &lt;object_2&gt; 
      .
      . 
      .
      &lt;/object_n&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>Aim is to parse this multilevel nesting. A few classes are defined in Java.</p>
  
  <pre><code>Class Object_1
  Class Object_2
  .
  .
  .
  Class Object_N
  </code></pre>
  
  <p>with their respective properties. </p>
  
  <p>The following code is working for me, but then this is not the best way of doing things. </p>
  
  <pre><code>File file = new File(fileName);
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(file);
  doc.getDocumentElement().normalize();
  
  if(doc ==null) return;
  
  Node node = doc.getFirstChild();
  
  NodeList lst = node.getChildNodes();
  Node children = null ; 
  
  int len = lst.getLength();
  for(int index=0;index&lt;len;index++)
  {
      Node child = lst.item(index);
      String name = child.getNodeName();
      if(name=="Name")
          name = child.getNodeValue();
      else if(name=="Comment")
          comment = child.getNodeValue());
      else if(name=="children")
          children = child;
      }
  
      if(children==null) return; 
  
      lst = children.getChildNodes();
      len = lst.getLength();
      Class&lt;?&gt; obj=null;
      AbsModel model = null;
      for(int index=0;index&lt;len;index++)
      {
          Node childNode = lst.item(index);
          String modelName = childNode.getNodeName();
          try {
              obj = Class.forName(modelName);
          } catch (ClassNotFoundException e) {
              e.printStackTrace();
          }
          if(obj!=null)
              model = (AbsModel) obj.newInstance();
          else
              model = new GenericModel();
  
          model.restoreDefaultPropFromXML(childNode);
          addChild(model);
      }
  }
  </code></pre>
  
  <p>Is there a better way of parsing this XML. </p>