How to read XML file in Java using DOM

  • 12 July 2016
  • ADM

 

How to read XML file in Java using DOM - images/logos/java.jpg

 

In this tutorial, I will use the output from How to create XML file in java using DOM tutorial, plus a small adding, in terms of 2 users.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<users>
  <user id="100">
    <name>John Doe</name>
    <email>john.doe@example.com</email>
  </user>
  <user id="200">
    <name>ADM Factory</name>
    <email>adm.factory@example.com</email>
  </user>
</users>

Example 1

In this example, I will use getElementsByTagName to get all the user elements. This is useful for simple XML files with fixed fields.

package com.admfactory.xml;

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 XMLRead1 {

    public static void main(String[] args) {
	try {
	    String filePath = "C:\\admfactory\\users.xml";

	    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

	    Document doc = docBuilder.parse(filePath);

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

	    for (int i = 0; i < nList.getLength(); i++) {
		Node node = nList.item(i);
		Element element = (Element) node;
		printElement(element);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
    
    public static void printElement(Element element) {
	System.out.println("--------------------------------");
	System.out.println("element type: " + element.getNodeName());
	System.out.println("attribute id: " + element.getAttribute("id"));
	System.out.println("element name: " + element.getElementsByTagName("name").item(0).getTextContent());
	System.out.println("element email: " + element.getElementsByTagName("email").item(0).getTextContent());	
	System.out.println("--------------------------------");
	System.out.println();
    }
}

Output

--------------------------------
element type: user
attribute id: 100
element name: John Doe
element email: john.doe@example.com
--------------------------------

--------------------------------
element type: user
attribute id: 200
element name: ADM Factory
element email: adm.factory@example.com
--------------------------------

Example 2

When you have more complex XML file structure and when not all the elements are present it might be useful to parse through all nodes and read the values. The same for attributes.

package com.admfactory.xml;

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

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

public class XMLRead2 {

    public static void main(String[] args) {
	try {
	    String filePath = "C:\\admfactory\\users.xml";

	    /** create the Document object */
	    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

	    Document doc = docBuilder.parse(filePath);

	    if (doc.hasChildNodes()) {
		printNodeList(doc.getChildNodes());
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * 
     * print all the attributes from the element
     *
     * @param element
     */
    public static void printAttribute(Node element) {
	NamedNodeMap attributes = element.getAttributes();
	if (attributes == null)
	    return;
	for (int i = 0; i < attributes.getLength(); i++) {
	    Node attribute = attributes.item(i);
	    System.out.println("attribute " + attribute.getNodeName() + ": " + attribute.getNodeValue());
	}
    }

    /***
     * 
     * print all the elements data
     *
     * @param list
     */
    public static void printNodeList(NodeList list) {
	for (int i = 0; i < list.getLength(); i++) {
	    Node node = list.item(i);
	    if (node.getNodeType() == Node.ELEMENT_NODE) {
		System.out.println("element " + node.getNodeName() + ": " + node.getTextContent());

		/** Print the attributes */
		if (node.hasAttributes()) {
		    printAttribute(node);
		}

		/** if the elements contains children print those too */
		if (node.hasChildNodes()) {
		    printNodeList(node.getChildNodes());
		}
	    }
	}
    }
}

Output

element users: 
 
 John Doe
 john.doe@example.com
 
 
 ADM Factory
 adm.factory@example.com
 

element user: 
 John Doe
 john.doe@example.com
 
attribute id: 100
element name: John Doe
element email: john.doe@example.com
element user: 
 ADM Factory
 adm.factory@example.com
 
attribute id: 200
element name: ADM Factory
element email: adm.factory@example.com

The output looks more complicated but this example will parse any xml file structure.

 

References