DOMXPath 根据前一个同级值获取同级
假设我有这个:
<foo>
<bar>CCC</bar>
<baz>sometexthere</baz>
</foo>
<foo>
<bar>AAA</bar>
<baz>sometext</baz>
</foo>
<foo>
<bar>DDD</bar>
<baz>something</baz>
</foo>
现在,我想获取 baz 值,该值紧随 bar 之后,值为 AAA (!但是仅具有值AAA!)。我不知道我有多少个“foo”,所以我不能准确地写出这样的内容:
$element->item(0) // I don't know the exact number
那么我怎样才能获得 baz 的值,它跟在 bar 之后,具有特定的值?
(对于上面的示例,我想获得 sometext 因为它位于 AAA 之后)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有不同的方法来编写匹配的 XPath,具体取决于您希望如何执行匹配。这里有一些选项:
找到一个 baz,其中还有一个
AAA
,但不一定在它前面(它可能在后面,或者中间可能有其他元素):查找前面为
AAA
的 baz:查找立即 前面的 baz
AAA
:查找
AAA
并返回紧随其后的任何元素,不一定名为 baz。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):Find a baz preceded by
<bar>AAA</bar>
:Find a baz immediately preceded by
<bar>AAA</bar>
:Find a
<bar>AAA</bar>
and return whatever element comes immediately after it, not necessarily named baz.基本查询是查找包含
AAA
的bar
,然后导航到相应的baz
元素。或者,查找所有
baz
并根据关联的bar
进行过滤。或者,
baz
位于foo
中,其中包含具有AAA
的bar
。如果您不熟悉 XPath 表达式,请为 XML 路径语言 (XPath) 添加书签以供稍后使用。
A basic query would be to find the
bar
s that containAAA
, then navigate to the correspondingbaz
element.Or, find all
baz
and filter based on the associatedbar
.Or,
baz
s withinfoo
s containingbar
havingAAA
.If you're not familiar with XPath expressions, bookmark XML Path Language (XPath) for later.