XPath搜索多个嵌套元素

时间:2013-05-09 19:25:09

标签: html xml xpath xml-parsing

我有以下html文档

<div class="books">
  <div class="book">
    <div>
      there are many deep nested elements here, somewhere there will be one span with  some text e.g. 'mybooktext' within these
      <div>
        <div>
          <div>
            <span>mybooktext</span>
          </div>
       </div>
     </div>
  </div>
<div>
 there are also many nested elements here, somewhere there will be a link with a class called 'mylinkclass' within these. (this is the element i want to find)
 <div>
   <div>
     <a class="mylinkclass">Bla</a>
   </div>
 </div>
</div>
</div>
<div class="book">
<div>
 there are many deep nested elements here, somewhere there will be one span with some     text e.g. 'mybooktext' within these
   <div>
     <span>mybooktext</span>
   </div>
 <div>
</div>
<div>
 there are also many nested elements here, somewhere there will be a link with a class called 'mylinkclass' within these. (this is the element i want to find)
 <div>
   <a class="mylinkclass">Bla</a>
 </div>
</div>
</div>
<div class="book">
same as above
</div>
</div>

我想在book元素中找到link元素(链接有名为'mylinkclass'的类),这将基于同一book元素中span的文本。

所以它会是这样的:

  1. - 使用文本'mybooktext'

  2. 查找范围
  3. 向上推荐Book div

  4. - 在图书div中查找“mylinkclass”类的链接

  5. 这应该使用一个xpath语句

    来完成

1 个答案:

答案 0 :(得分:7)

在我的少数人中,这是你在寻找:

" //span[contains(text(),'mybooktext')]
            /ancestor::div[@class='book']
            //a[@class='mylinkclass']" 

//span[contains(text(),'mybooktext')]查找含有“mybooktext”的san /ancestor::div[@class='book']导航书籍div(在任何深处)
//a[@class='mylinkclass']在book div(任何深层)中找到类'mylinkclass'的链接

更新: 将第一个条件改为
//span[(text() ='mybooktext']如果mybooktext是span

中的唯一文本