Read XML File In Java Example – (DOM Parser)

Chapter: XML Last Updated: 15-07-2016 13:57:08 UTC

Program:

            /* ............... START ............... */
                
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class JavaReadXMLFileDomParser {
	public static void main(String argv[]) {

		try {

			File fXmlFile = new File("c:/staff.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);

			doc.getDocumentElement().normalize();

			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

			NodeList nList = doc.getElementsByTagName("staff");

			System.out.println("----------------------------");

			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);

				System.out.println("\nCurrent Element :" + nNode.getNodeName());

				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element eElement = (Element) nNode;

					System.out.println("Staff id : " + eElement.getAttribute("id"));
					System.out.println(
							"First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
					System.out.println(
							"Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
					System.out.println(
							"Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
					System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
                /* ............... END ............... */
        

Output

Root element :company  
Current Element :staff
Staff id : 1001 
First Name : Staff1 
Last Name : last name 
Nick Name : Nick
Salary : 100000
 
Current Element :staff 
Staff id : 2001 
First Name : Staff2 
Last Name : lastname 
Nick Name : Nick1 
Salary : 200000

Notes:

  • DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.

Tags

Read XML File, Java

Similar Programs Chapter Last Updated
XML File Creation In Java Example – (DOM Parser) XML 06-07-2016
Modify XML File In Java Example – (DOM Parser) XML 15-07-2016
Count XML Elements In Java Example – (DOM Parser) XML 11-06-2016

1