且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 XPath 选择具有特定属性的第一个元素

更新时间:2023-01-08 10:56:52

使用:

(/bookstore/book[@location='US'])[1]

这将首先获得 location 属性等于 'US' 的 book 元素.然后它将从该集合中选择第一个节点.请注意括号的使用,这是某些实现所必需的.

This will first get the book elements with the location attribute equal to 'US'. Then it will select the first node from that set. Note the use of parentheses, which are required by some implementations.

请注意,这与 /bookstore/book[1][@location='US'] 不同,除非第一个元素也恰好具有该位置属性.

Note, this is not the same as /bookstore/book[1][@location='US'] unless the first element also happens to have that location attribute.