Online-Academy

Look, Read, Understand, Apply

Menu

Reading XML File

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person>
	<fn>Raj</fn>
	<ln>Mudwari</ln>
	</person>
	<person>
	<fn>Laurel</fn>
	<ln>Jonshan</ln>
	</person>
</persons>

To read XML document, we need objects of following classes:
  • DocumentBuilderFactory
  • DocumentBuilder
  • Document
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("persons.xml"));
NodeList nl = document.getElementsByTagName("person");
returns NodeList
item method of NodeList object is used to refer node.
Node p = nl.item(index);
Node p is to be casted to Element and assigned to Element object
Element pp = (Element) p;
If node has child nodes, those nodes can be accessed using pp.getChildNodes().
import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class personxmlReader {
    public static void main(String[] args) {
    	try {
            File inputFile = new File("persons.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder;
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse("persons.xml");
          
            NodeList nodeList = doc.getElementsByTagName("person");
            System.out.println("Number: "+nodeList.getLength());
            for (int i = 0; i < nodeList.getLength(); i++) {
                 Node node = nodeList.item(i); 
                 {
                	 if(node.getNodeType()==Node.ELEMENT_NODE) {
                     Element elem = (Element) node;
                     NodeList nl = elem.getChildNodes();
                     for(int j=0;j<nl.getLength();j++)
                     {
                    	 Node n = nl.item(j);
                    	 if(n.getNodeType()==Node.ELEMENT_NODE) {
                    		 Element el = (Element) n;
                    		 System.out.println(el.getTagName()+","+el.getTextContent());		 
                    	 }
                     }
                	 }
                 }
            }
    	}catch(Exception e) {
    	}
    	}
}