How to get attribute value using XPath in Java?
42,105
Solution 1
Like this:
XPathExpression expr = xpath.compile("/schema/element[@id='name_id_2']/@name");
Your expression attempts to select the text inside the name
element, instead of the value of the name
attribute.
Solution 2
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class XMLXpathReadder {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new FileInputStream(new File("C:\\Test.xml")));// same xml comments as above.
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
Element userElement = (Element) xpath.evaluate("/schema/element", document,
XPathConstants.NODE);
System.out.println(userElement.getAttribute("id"));
System.out.println(userElement.getAttribute("name"));
}
}
Above Code work for me.
But how to read values of all elements. I am getting always first elements node only.
<?xml version="1.0" encoding="UTF-8"?>
<schema>
<element name="name_ele1" id="_1" >test name1</element>
<element name="name_ele2" id="_2" >test name2</element>
<element name="name_ele2" id="_3" >test name3</element>
</schema>
![Mohd Arshil](https://i.stack.imgur.com/gALz0.jpg?s=256&g=1)
Author by
Mohd Arshil
Updated on May 25, 2020Comments
-
Mohd Arshil about 4 years
I have below XML to parse using XPath:
<?xml version="1.0" encoding="UTF-8"?> <schema> <element name="name_ele1" id="name_id_1" >test name1</element> <element name="name_ele2" id="name_id_2" >test name2</element> <element name="name_ele2" id="name_id_3" >test name3</element> </schema>
I want to fetch "name" from the xml document based upon the Id I have passed but I am not able to get the required data instead query is returning blank.
XPathExpression expr = xpath.compile("/schema/element[@id='name_id_2']/name/text()");
-
Jens Erat almost 10 yearsYou're using XPath, not XQuery. Java doesn't support XQuery out of the box.
-
-
Mohd Arshil almost 10 yearsthank you the following expression solved the mentioned problem
-
Ahamed Abdul Rahman over 4 yearsInstead of XPathConstants.NODE, try with XPathConstants.NODESET 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()); } . Please check this link: howtodoinjava.com/xml/java-xpath-tutorial-example