是否有更好的方式获取XPath查询结果的父节点? [英] Is there a better way of getting parent node of XPath query result?

查看:104
本文介绍了是否有更好的方式获取XPath查询结果的父节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这样的标记:

 < 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> and some text ONLY if adjacent span is of class a1. So at the end of the whole code my result is <a> from first div and some text from third one. It'd be easy if <a> and some text were inside span or div would have class attribute, but no luck. What I'd do is query for span with a1 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆