Learn to parse an XML document and read the value of an attribute using XPath in Java. We can read the attribute value for all its occurrences in the document, or only for selected nodes in the XML.
1. XPath Expression for Attributes
In XPath, the ‘@’ is used to access the attributes. For example, the following expression will return the value of an attribute for all occurrences of a specified node.
/path to/node/@attribute_name
If we want to find the attribute value for a specific node only, we can use the node filter expression and attribute name in the expression as follows:
/path to/node[filter-expression]/@attribute_name
2. Java Program to Get Attribute Value using XPath
The following Java program demonstrates the usage of both cases discussed above. We have the following XML file in which we will be searching for the attribute values.
<?xml version="1.0" encoding="utf-8" ?>
<inventory>
<!--Test is test comment-->
<book year="2000">
<title>Snow Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
<book year="1995">
<title>Zodiac</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553573862</isbn>
<price>7.50</price>
</book>
</inventory>
Next, we will build an instance of XPathExpression as described in the XPath tutorial.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("inventory.xml");
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
Then we will use this expression to get the values of the attribute.
Get attribute value of all occurrences for attribute
XPathExpression expr = xpath.compile("//book/@year");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Program output.
2000
2005
1995
Get attribute value only for filtered nodes
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/@year");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Program output.
2000
1995
Happy Learning !!
Leave a Reply