What is the correct XPath for choosing attributes

2020-01-24 20:00发布

Given this XML, what XPath returns all elements whose prop attribute contains Foo (the first three nodes):

<bla>
 <a prop="Foo1"/>
 <a prop="Foo2"/>
 <a prop="3Foo"/>
 <a prop="Bar"/>
</bla>

标签: xml xpath
9条回答
戒情不戒烟
2楼-- · 2020-01-24 20:24

try this:

//a[contains(@prop,'foo')]

that should work for any "a" tags in the document

查看更多
够拽才男人
3楼-- · 2020-01-24 20:27
descendant-or-self::*[contains(@prop,'Foo')]

Or:

/bla/a[contains(@prop,'Foo')]

Or:

/bla/a[position() <= 3]

Dissected:

descendant-or-self::

The Axis - search through every node underneath and the node itself. It is often better to say this than //. I have encountered some implementations where // means anywhere (decendant or self of the root node). The other use the default axis.

* or /bla/a

The Tag - a wildcard match, and /bla/a is an absolute path.

[contains(@prop,'Foo')] or [position() <= 3]

The condition within [ ]. @prop is shorthand for attribute::prop, as attribute is another search axis. Alternatively you can select the first 3 by using the position() function.

查看更多
爷、活的狠高调
4楼-- · 2020-01-24 20:28

For the code above... //*[contains(@prop,'foo')]

查看更多
登录 后发表回答