是否有更好的方式获取XPath查询结果的父节点? [英] Is there a better way of getting parent node of XPath query result?
问题描述
< div class =foo>
< div>< span class =a1>< / span>< a href =...> ...< / a>< / div>
< div>< span class =a2>< / span>< a href =...> ...< / a>< / div>
< div>< span class =a1>< / span>一些文本< / div>
< div>< span class =a3>< / span>一些文本< / div>
< / div>
现在我有兴趣获得这些< a>
和一些文本
只有相邻的 span
是class a1
。所以在整个代码的结尾,我的结果是从第一个 div
和< a>
>一些文本从第三个。如果< a>
和一些文本
在 span
或
div
将有 class
属性,但没有运气。我要做的是查询 span
与 a1
class:
// div [contains(@ class,'foo')] / div / span [contains(@ class,'a1')]
,然后获取其父级,并与该父节点另行执行 query()
上下文节点。有没有更好的办法呢?我正在使用PHP DOM,如果这样会很重要。
ANSWER
< blockquote>
根据@MarcB答案,正确的查询是:
// div [contains(@ class,'foo')] / div / span [contains(@ class,'a1')] / ..
,但对于
< A>
可能会更好地使用:// div [contains(@ class,'foo')] / div / span [contains(@ class,'a1')] /../ a
得到
< A>
而不是其容器。 >
解决方案关于xpath查询的好处是,您可以像文件系统路径一样对待它们,因此只需使用
// div [contains(@ class,'foo')] / div / span [contains(@ class,'a1')]
^^
将找到.foo节点下的所有.a1节点,日en向上移动一级到a1节点的父母。
Given markup like this:
<div class="foo"> <div><span class="a1"></span><a href="...">...</a></div> <div><span class="a2"></span><a href="...">...</a></div> <div><span class="a1"></span>some text</div> <div><span class="a3"></span>some text</div> </div>
Now I am interested in getting these
<a>
andsome text
ONLY if adjacentspan
is of classa1
. So at the end of the whole code my result is<a>
from firstdiv
andsome text
from third one. It'd be easy if<a>
andsome text
were insidespan
ordiv
would haveclass
attribute, but no luck. What I'd do is query forspan
witha1
class://div[contains(@class,'foo')]/div/span[contains(@class,'a1')]
and then get its parent and do another
query()
with that parent node as context node. Is there any better way to do that? I am using PHP DOM if that would matter.ANSWER
As per @MarcB answer, the right query is:
//div[contains(@class,'foo')]/div/span[contains(@class,'a1')]/..
but for
<A>
it may be better to use://div[contains(@class,'foo')]/div/span[contains(@class,'a1')]/../a
the get the
<A>
instead of its container.解决方案The nice thing about xpath queries is that you can essentially treat them like a file system path, so simply having
//div[contains(@class,'foo')]/div/span[contains(@class,'a1')]/.. ^^
will find all your .a1 nodes that are below a .foo node, then move up one level to the a1 nodes' parents.
这篇关于是否有更好的方式获取XPath查询结果的父节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!