Your Computer Science Resource

Simple XML Reader

Nowadays XML is a popular format for configuration files and transferring messages across networks. For reading node values from an XML file, I’ve created a small utility class. There are two useful methods in this class, getElementValue() and getElementValues(). In this article, I will briefly show how you can read in values from an XML file using this simple class.

The Code

Most of this is pretty self-explanatory. getElementValue() returns one String of a node value and if there are multiple nodes, it returns the first node String value. getElementValues() returns a List of String values which is more useful for nodes which you know have multiple child nodes. In the test class, you will see how to use both of these methods.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlReader {

    /**
     * Returns a Document object from a given
     * XML file.
     *
     * @param File xmlFile
     * @return Document
     */

    public static Document getDocumentFromXml( File xmlFile ) {

        Document doc = null;

        try {

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse( xmlFile );
            doc.getDocumentElement().normalize();

        } catch (ParserConfigurationException e) {

            e.printStackTrace();

        } catch (SAXException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return doc;

    }

    /**
     * Returns the first element value if there
     * are multiple elements for this node.
     *
     * @param File xmlFile
     * @param String parentTag
     * @param String elementTag
     * @return String elementValue
     */

    public static String getElementValue( File xmlFile, String parentTag, String elementTag ) {

        String toReturn = "";

        try {

            Document doc = getDocumentFromXml( xmlFile );

            // Get all nodes under the parent node

            NodeList nodes = doc.getElementsByTagName( parentTag );

            for( int i = 0; i < nodes.getLength(); i++ ) {

                Node currentNode = nodes.item( i );

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

                    Element currentElement = (Element) currentNode;
                    NodeList childNodes = currentElement.getElementsByTagName( elementTag );

                    // Return the first node

                    toReturn = childNodes.item( 0 ).getChildNodes().item( 0 ).getNodeValue();

                }

            }

        } catch ( NullPointerException e ) {

            /**
             * A NPE will be thrown if the element tag
             * does not exist. Just return an empty
             * String in this case.
             */

        } catch ( Exception e ) {

            e.printStackTrace();

        }

        return toReturn;

    }

    /**
     * This returns a list of all elements
     * for the specified node.
     *
     * @param File xmlFile
     * @param String parentTag
     * @param String elementTag
     * @return List<String> elementValues
     */
    public static List<String> getElementValues( File xmlFile, String parentTag, String elementTag ) {

        List<String> toReturn = new ArrayList<String>();

        try {

            Document doc = getDocumentFromXml( xmlFile );

            // Get all nodes under the parent node

            NodeList nodes = doc.getElementsByTagName( parentTag );

            for( int i = 0; i < nodes.getLength(); i++ ) {

                Node currentNode = nodes.item( i );

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

                    Element currentElement = (Element) currentNode;
                    NodeList nameNodeList = currentElement.getElementsByTagName( elementTag );

                    for ( int j = 0; j < nameNodeList.getLength(); j++ ) {

                        NodeList names = nameNodeList.item( j ).getChildNodes();
                        toReturn.add( names.item(0).getNodeValue() );

                    }

                }

            }

        } catch ( NullPointerException e ) {

            /**
             * A NPE will be thrown if the element tag
             * does not exist. Just return an empty list
             * in this case.
             */

        } catch ( Exception e ) {

            e.printStackTrace();

        }

        return toReturn;

    }

}

A Small Test

Suppose I have a configuration XML file:

<?xml version="1.0"?>
<configuration>
	<application>
		<name>Test App</name>
		<author>John Smith</author>
		<version>1.0</version>
		<languages>
			<language>English</language>
			<language>Spanish</language>
			<language>Italian</language>
		</languages>
	</application>
</configuration>

Here’s how to read every node value in this XML file:

import java.io.File;
import java.util.List;

public class XMLTest {

	public static void main( String[] args ) {

	    File xmlFile = new File("config/config.xml");

	    String name = XmlReader.getElementValue( xmlFile, "application", "name" );
	    String version = XmlReader.getElementValue( xmlFile, "application", "version");
		String author = XmlReader.getElementValue( xmlFile, "application", "author" );

		List<String> languages = XmlReader.getElementValues( xmlFile, "languages", "language" );

		System.out.println("Application Name: " + name);
		System.out.println("Application Version: " + version);
		System.out.println("Author: " + author);
		System.out.println("Supported Languages: " + languages);

	}

}

Output

Application Name: Test App
Application Version: 1.0
Author: John Smith
Supported Languages: [English, Spanish, Italian]

Tags:

Leave a Reply