如何在 Java 中使用 XPath 获取属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25259836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get attribute value using XPath in Java?
提问by Mohd Arshil
I have below XML to parse using XPath:
我有以下 XML 可以使用 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.
我想根据我传递的 Id 从 xml 文档中获取“名称”,但我无法获取所需的数据,而是查询返回空白。
XPathExpression expr = xpath.compile("/schema/element[@id='name_id_2']/name/text()");
采纳答案by Robby Cornelissen
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.
您的表达式尝试选择name
元素内的文本,而不是name
属性的值。
回答by Laxman G
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>