How to read an XML attribute value

idea bulb: xml attibutesThere are a number of methods to read an XML attribute value. We present two common methods here:

This example uses the library XML document as a reference. For the purpose of this example we will retrieve the name of the first category: dogs.

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <category name="dogs">
        <book>
            <title lang="english">All about dogs</title>
            <author>Someone</author>
            <isin>true</isin>
            <daysuntilreturn>0</daysuntilreturn>
            <price>15.10</price>
        </book>
    </category>
     <category name="cats">
        <book>
            <title lang="english">All about cats</title>
            <author>Someone</author>
            <isin>false</isin>
            <daysuntilreturn>3</daysuntilreturn>
            <price>12.00</price>
        </book>
        <book>
            <title lang="zulu">Konke mayelana ikati</title>
            <author>Else</author>
            <isin>true</isin>
            <daysuntilreturn>0</daysuntilreturn>
            <price>25.99</price>
        </book>
    </category>
</library>

 

Method 1: Locate & Read an attribute value using the XML DOM

The DOM method is included here for completeness and also to contrast it against the XPATH method.

Java

The Java implementation of the W3C XML Document Object Model (DOM) provides a number of methods to retrieve an attribute node value:

getElementsByTagName()Returns a node list of all child elements with the specified tag name. The nodes are returned in the same order as they appear in the source XML document.
getAttributes()
getNamedItem()
Used together it returns a list of all attributes which is filtered by name to retrieve the item we are interested in.
getNodeValue()The method returns the text value of a given text node.

The following example illustrates how to retrieve an element node value using the XML DOM. It should be noted that the code sample does not implement any error checking.

import org.w3c.dom.Document;

public class ExampleClass {

    /**
     * Retrieves the first category name found.
     * @return the string value.
     */
    public String getAttributeValue() {
        Document xmlDocument = loadXMLDocument();
        return xmlDocument.getElementsByTagName("category").item(0).getAttributes().getNamedItem("name").getNodeValue();
    }
}

 

Note:

  1. The method will throw a NullPointerException if any of the target nodes are not found.
  2. This method becomes more complex (and error prone) if the target node is deep in the document hierarchy.

 

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!

Method 2: Locate & Read an element value using XPATH expressions

The XPATH method is an alternative to DOM manipulation. This method uses an XPATH expression to evaluate the source document and return a value. From our perspective this is the preferred method to locate and then read an element node in XML. XPATH is specifically designed to meet this requirement.

In this example the key aspect is the XPATH expression.

/library/category/@name

This expression refers to an specific attribute in the document hierarchy: name. The expression can be tailored to meet your specific requirements by using the selection methods, predicates, axis, and etc. Refer to the XPATH Tutorial for instruction on how to use XPATH expression. In this specific case the expression selects the first category node found and its name attribute.

Java

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class ExampleClass {

    /**
     * Retrieves the first category name found
     *
     * @return the string value; or null if the node was not found.
     * @throws XPathExpressionException thrown if the XPATH expression cannot be evaluated.
     */
    public String getAttributeValue() throws XPathExpressionException {
        Document xmlDocument = loadXMLDocument();
        XPathFactory _xpathFactory = XPathFactory.newInstance();
        XPath _xpath = _xpathFactory.newXPath();
        XPathExpression exp = _xpath.compile("/library/category/@name");
        return exp.evaluate(xmlDocument);
    }
}

 

 

Note:

  1. The method will throw an XPathExpressionException if the XPATH expression is invalid – cannot be compiled or evaluated. The method will simply return null if the target node does not exist.
  2. The method logic remains the same if the target attribute is deeper in the document hierarchy. The XPATH expression changes to reflect the new location of the target attribute.
  3. Refrain from using wildcards in the XPATH expression. Doing so can have an adverse effect on performance. (especially ‘//’)

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 example returns a string value from the XPathExpression.evaluate() method call.  Also, the XPATH approach differs in another significant way from the XML DOM method: XPATH can return different data types as the result from the evaluate() method when you supply the necessary data type indicator.

Posted in XML, XPATH and tagged , .

Leave a Reply