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:03
//a[contains(@prop,'Foo')]

Works if I use this XML to get results back.

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

Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use

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

This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element

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

I added this for the sake of thoroughness and in the spirit of stackoverflow. :)

查看更多
啃猪蹄的小仙女
3楼-- · 2020-01-24 20:03

Have you tried something like:

//a[contains(@prop, "Foo")]

I've never used the contains function before but suspect that it should work as advertised...

查看更多
贼婆χ
4楼-- · 2020-01-24 20:05

This XPath will give you all nodes that have attributes containing 'Foo' regardless of node name or attribute name:

//attribute::*[contains(., 'Foo')]/..

Of course, if you're more interested in the contents of the attribute themselves, and not necessarily their parent node, just drop the /..

//attribute::*[contains(., 'Foo')]
查看更多
Emotional °昔
5楼-- · 2020-01-24 20:05

/bla/a[contains(@prop, "foo")]

查看更多
聊天终结者
6楼-- · 2020-01-24 20:13

If you also need to match the content of the link itself, use text():

//a[contains(@href,"/some_link")][text()="Click here"]

查看更多
成全新的幸福
7楼-- · 2020-01-24 20:23

John C is the closest, but XPath is case sensitive, so the correct XPath would be:

/bla/a[contains(@prop, 'Foo')]
查看更多
登录 后发表回答