如何在Java中使用XPath获取属性值? [英] How to get attribute value using XPath in Java?
本文介绍了如何在Java中使用XPath获取属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我下面有XML可以使用XPath进行解析:
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>
我想根据传递的ID从xml文档中获取名称",但是我无法获取所需的数据,而是查询返回空白.
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()");
推荐答案
像这样:
XPathExpression expr = xpath.compile("/schema/element[@id='name_id_2']/@name");
您的表达式尝试选择 name
元素内的文本,而不是 name
属性的值.
Your expression attempts to select the text inside the name
element, instead of the value of the name
attribute.
这篇关于如何在Java中使用XPath获取属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文