开发者

XPath find attributes with specific values

开发者 https://www.devze.com 2023-01-25 09:16 出处:网络
I am sure this should be easier than I\'m making it but I\'m trying to get the following response from my source.Please could somebody help me with the xpath?

I am sure this should be easier than I'm making it but I'm trying to get the following response from my source. Please could somebody help me with the xpath?

I am开发者_C百科 trying to select the line elements with the values "extract". In real world, I'm reading a text file and using xml and want to pick out the lines which read extract.

Source

<line>
<line number="1">blah</line>
<line number="2">extract</line>
<line number="3">blah</line>
<line number="4">extract</line>
</line>

Required Response:

<line>
<line number="2">extract</line>
<line number="4">extract</line>
</line>

or even just

extract

extract

would be fine.

Many Thanks,


Use:

/*/*[.='extract']/text()

or even:

//text()[.='extract']


This (use = if you use XPath 1.0):

/line/line[text() eq 'extract']/text()

will give you: (See evaluation)

extract
extract

The reason why //line is not a good idea, is that you use line tags for 2 things (your top tag line and your childs of line) - you should not do that :-/. If you want the elements instead of the text, you can write:

/line/line[text() eq 'extract']

And last, this will give you the count (it seems it is what you really need?)

count(/line/line[text() eq 'extract'])


Since your subject mentions attributes (even if your question doesn't) I assume you want to find the value of the number attribute for all matching lines. If so:

/line/line[text()='extract']/@number


//line[contains(text(), 'extract')]

EDIT: This works for XPath 1.0, and it obviously searches for the string (rather than requiring equality).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号