How to parse XML data values using XPATH

XML is a simple text format by design, however, XPATH defines multiple data types which allow for more robust calculation and comparison operations in XSLT and programming languages.This example illustrates how you can use XPATH expressions to:

  • Parse Boolean values in XML
  • Parse Number (Integer, Double, Float, …) values in XML
  • Parse String values in XML
  • Locate a Node and NodeLists in XML

Java

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

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

public class ExampleClass {


    /**
     * Retrieves a numeric value from the given root node.
     * 
     * @param targetpath the xpath location.
     * @return A Number instance; otherwise null if nothing was found at the xpath location.
     */
    public Number getNumber(String targetpath) {
        Document xmlDocument = loadXMLDocument();
        XPathFactory _xpathFactory = XPathFactory.newInstance();
        XPath _xpath = _xpathFactory.newXPath();
        XPathExpression exp = _xpath.compile(targetpath);
        return (Number) exp.evaluate(xmlDocument,  XPathConstants.NUMBER);
    }
    
    /**
     * Retrieves a boolean value from the xml document.
     * 
     * @param targetpath the xpath location.
     * @return <code>true</code> if parsed to true; otherwise <code>false</code> .
     */
    public Boolean getBoolean(String targetpath) {
        Document xmlDocument = loadXMLDocument();
        XPathFactory _xpathFactory = XPathFactory.newInstance();
        XPath _xpath = _xpathFactory.newXPath();
        XPathExpression exp = _xpath.compile(targetpath);
        return (Boolean) exp.evaluate(xmlDocument, XPathConstants.BOOLEAN);
    }
    
    /**
     * Retrieves a string value from the given root node.
     * 
     * @param targetpath the xpath location.
     * @return String value in the node defined by xpath; otherwise null if nothing was found at the xpath location.
     */
    public String getString(String targetpath) {
        Document xmlDocument = loadXMLDocument();
        XPathFactory _xpathFactory = XPathFactory.newInstance();
        XPath _xpath = _xpathFactory.newXPath();
        XPathExpression exp = _xpath.compile(targetpath);
        return (String) exp.evaluate(xmlDocument, XPathConstants.STRING);
    }
    
    /**
     * Retrieves a node defined by the given xpath from the xml document.
     * 
     * @param targetpath the xpath location.
     * @return A node instance if found; otherwise null if nothing was found at the xpath location.
     */
    public Node getNode(String targetpath) {
        Document xmlDocument = loadXMLDocument();
        XPathFactory _xpathFactory = XPathFactory.newInstance();
        XPath _xpath = _xpathFactory.newXPath();
        XPathExpression exp = _xpath.compile(targetpath);
        return (Node) exp.evaluate(xmlDocument, XPathConstants.NODE);
    }
    
    /**
     * Retrieves a list of nodes defined by the given xpath from the xml document.
     * 
     * @param targetpath the xpath location.
     * @return
     */
    public NodeList getNodeList(String targetpath) {
        Document xmlDocument = loadXMLDocument();
        XPathFactory _xpathFactory = XPathFactory.newInstance();
        XPath _xpath = _xpathFactory.newXPath();
        XPathExpression exp = _xpath.compile(targetpath);
        return (NodeList) exp.evaluate(xmlDocument,  XPathConstants.NODESET);
    }
}


 

C#

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Visual Basic

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

The benefits of this method for parsing typed values from XML are immediately apparent:

  • Values can be immediately referenced from an XPATH expression rather than traversing the DOM hierarchy.
  • Data type validation/conversion is implicit in the retrieval method.
  • Data value defaults are implicit in the retrieval method: Boolean = false; Number = 0; String = “”.
  • Null-valued objects are returned if the target XML element does not exist

An example using our fictional library XML illustrates how this approach works.

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <category name="dogs">
        <book>
            <name>All about dogs</name>
            <author>Someone</author>
            <isin>true</isin>
            <daysuntilreturn>0</daysuntilreturn>
        </book>
    </category>
     <category name="cats">
        <book>
            <name>All about cats</name>
            <author>Someone</author>
            <isin>false</isin>
            <daysuntilreturn>3</daysuntilreturn>
        </book>
    </category>
</library>

 

To retrieve the number of days when the ‘All about cats’ book must be returned:

Java

public Integer daysUntilCatReturns(){
    Document xmlDocument = loadXMLDocument();
    XPathFactory _xpathFactory = XPathFactory.newInstance();
    XPath _xpath = _xpathFactory.newXPath();
    XPathExpression exp = _xpath.compile("/library/category[name()='cats']/book[1]/daysuntilreturn");
    return (Integer) exp.evaluate(xmlDocument, XPathConstants.NUMBER);
}

 

C#

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Visual Basic

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Or simply use the reusable methods from the first example:

Java

public Integer daysUntilCatReturns(){
        return getNumber("/library/category[name()='cats']/book[1]/daysuntilreturn");
}

 

C#

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Visual Basic

No example – YET…

This is an ongoing project – Be sure to follow our site as we are constantly adding new content just for you! If you have a special request, contact us and let us know!

Posted in XPATH and tagged , .

Leave a Reply