html - XPath 搜索多个嵌套元素

标签 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 元素中找到链接元素(链接具有名为“mylinkclass”的类),这将基于同一 book 元素中跨度的文本。

所以它会是这样的:

  1. -查找带有文本“mybooktext”的跨度

  2. -向上导航 Book div

  3. -在 book div 中查找类 'mylinkclass' 的链接

这应该使用一个 xpath 语句来完成

最佳答案

在我的几个中,这是您正在寻找的:

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

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

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

关于html - XPath 搜索多个嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16469563/

相关文章:

javascript - Soundmanager 2是否与html5音频有同样的麻烦?

html - Bootstrap 的新手 - 有一些移动样式问题

java - xpath 上下文的问题

c# - 使用 XSD : attribute is not declared. 进行 XML 验证但它是 - 请参见示例

php - PHP XPath 中的跳过值

c++ - 使用带有 TinyXPath 和 TinyXML 的 XPath 获取属性

java - 解析 XML 仅获取注释和日期值

javascript - 如何使用 ajax 上传文本字段和文件?

javascript - 带有 href 标签的图片库

xml - 可以在 XML 声明之前放置注释吗?