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 …
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>SnowCrash</title><author>NealStephenson</author><publisher>Spectra</publisher><isbn>0553380958</isbn><price>14.95</price></book><book year="2005"><title>BurningTower</title><author>LarryNiven</author><author>JerryPournelle</author><publisher>Pocket</publisher><isbn>0743416910</isbn><price>5.99</price></book><book year="1995"><title>Zodiac</title><author>NealStephenson</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.
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments