Java XML Document create from xml file

Description

Java XML Document create from xml file

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
   public static void main(String args[]) {
      try {/*from w  w w.  j  a  v  a 2s  . c  om*/
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("your.xml");
         Element root = doc.getDocumentElement();
         NodeList children = root.getChildNodes(); // get all children of root
         for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE)
               System.out.println(node.getFirstChild().getNodeValue());
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related