DOMXPath get sibling depending on previous sibling value

梦想的初衷 提交于 2020-01-04 01:27:50

问题


Let's say I have this:

<foo>
    <bar>CCC</bar>
    <baz>sometexthere</baz>
</foo>
<foo>
    <bar>AAA</bar>
    <baz>sometext</baz>
</foo>
<foo>
    <bar>DDD</bar>
    <baz>something</baz>
</foo>

Now, I want to get the baz value, which is coming right after bar with the value AAA (!but only with the value AAA!). I don't know how many "foo"s I have, so I can't exactly write something like:

$element->item(0) // I don't know the exact number

So how can I get the value of the baz, which follows after bar with a particular value?

(For the example above, I would like to get sometext because it comes after AAA)


回答1:


A basic query would be to find the bars that contain AAA, then navigate to the corresponding baz element.

//foo/bar[.="AAA"]/../baz

Or, find all baz and filter based on the associated bar.

//foo/baz[../bar = "AAA"]

Or, bazs within foos containing bar having AAA.

//foo[bar="AAA"]/baz

If you're not familiar with XPath expressions, bookmark XML Path Language (XPath) for later.




回答2:


There are different ways to write a matching XPath depending on exactly how you want the match to be performed. Here are some options:

Find a baz where there's also a <bar>AAA</bar>, not necessarily preceding it though (it could come after, or there could be other elements in between):

foo[bar = 'AAA']/baz

Find a baz preceded by <bar>AAA</bar>:

foo/baz[preceding-sibling::bar = 'AAA']
foo/bar[. = 'AAA']/following-sibling::baz

Find a baz immediately preceded by <bar>AAA</bar>:

foo/baz[preceding-sibling::*[1]/self::bar = 'AAA']
foo/bar[. = 'AAA']/following-sibling::*[1]/self::baz

Find a <bar>AAA</bar> and return whatever element comes immediately after it, not necessarily named baz.

foo/bar[. = 'AAA']/following-sibling::*[1]


来源:https://stackoverflow.com/questions/7139335/domxpath-get-sibling-depending-on-previous-sibling-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!