xml XPath按属性值选择元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14248063/
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
XPath to select Element by attribute value
提问by Pankaj
I have following XML.
我有以下 XML。
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee id="3">
<age>40</age>
<name>Tom</name>
<gender>Male</gender>
<role>Manager</role>
</Employee>
<Employee id="4">
<age>25</age>
<name>Meghna</name>
<gender>Female</gender>
<role>Manager</role>
</Employee>
</Employees>
I want to select Employee element with id="4".
我想选择 id="4" 的 Employee 元素。
I am using below XPath expression which is not returning anything.
我正在使用以下 XPath 表达式,它不返回任何内容。
//Employee/[@id='4']/text()
I checked it at http://chris.photobooks.com/xml/default.htmand it says invalid xpath, not sure where is the issue.
我在http://chris.photobooks.com/xml/default.htm 上检查过,它说 xpath 无效,不确定问题出在哪里。
回答by JLRishe
You need to remove the /before the [. Predicates (the parts in []) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text()at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.
您需要删除/之前[。谓词( 中的部分[])在它们之前不应该有斜线。此外,要选择 Employee 元素本身,您应该/text()在末尾留下 ,否则您只需选择 Employee 元素下方的空白文本值。
//Employee[@id='4']
Edit:As Jens points out in the comments, //can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a full path, for example:
编辑:正如 Jens 在评论中指出的那样,//可能会非常慢,因为它会在整个文档中搜索匹配节点。如果您正在处理的文档结构要保持一致,则最好使用完整路径,例如:
/Employees/Employee[@id='4']
回答by Gilles Quenot
Try doing this :
尝试这样做:
/Employees/Employee[@id=4]/*/text()
回答by rogerdpack
As a follow on, you could select "all nodes with a particular attribute" like this:
接下来,您可以选择“具有特定属性的所有节点”,如下所示:
//*[@id='4']

