Java xpath get attribute value xml
To get the value of an attribute in an XML using XPath in Java, you can use the javax.xml.xpath
package, which provides the XPath
class for evaluating XPath expressions. Here's an example of how to use XPath to get the value of an attribute:
Suppose you have the following XML document:
rrefe to:theitroad.com<book id="b001"> <title>The Catcher in the Rye</title> <author>J.D. Salinger</author> <price currency="USD">19.99</price> </book>
To get the value of the currency
attribute of the price
element, you can use the following Java code:
import java.io.StringReader; import javax.xml.xpath.*; import org.xml.sax.InputSource; import org.w3c.dom.*; String xml = "<book id=\"b001\">\n" + " <title>The Catcher in the Rye</title>\n" + " <author>J.D. Salinger</author>\n" + " <price currency=\"USD\">19.99</price>\n" + "</book>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); Document doc = builder.parse(is); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); String expression = "/book/price/@currency"; String currency = xpath.evaluate(expression, doc); System.out.println(currency); // Output: USD
In the above code, we first create a Document
object by parsing the XML using DocumentBuilder
and InputSource
. Then we create an XPath
object using XPathFactory
, and use it to evaluate the XPath expression "/book/price/@currency"
. The result is a String
containing the value of the currency
attribute, which we print to the console.