XPath按属性值选择元素 [英] XPath to select Element by attribute value

查看:44
本文介绍了XPath按属性值选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 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>

我想选择 id="4" 的 Employee 元素.

I want to select Employee element with id="4".

我正在使用以下 XPath 表达式,它不返回任何内容.

I am using below XPath expression which is not returning anything.

//Employee/[@id='4']/text()

我在 http://chris.photobooks.com/xml/default.htm 并显示无效的 xpath,不确定问题出在哪里.

I checked it at http://chris.photobooks.com/xml/default.htm and it says invalid xpath, not sure where is the issue.

推荐答案

您需要删除 [ 之前的 /.谓词([ ] 中的部分)在它们之前不应该有斜线.此外,要选择 Employee 元素本身,您应该在末尾省略 /text() ,否则您只需选择 Employee 元素下方的空白文本值.

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[@id='4']

正如 Jens 在评论中指出的那样,// 可能会非常慢,因为它会在整个文档中搜索匹配节点.如果您正在处理的文档结构要保持一致,则最好使用完整路径,例如:

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:

/Employees/Employee[@id='4']

这篇关于XPath按属性值选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆