如何使用 Xpath 根据其 parent 的兄弟 child 的文本查找元素

How to find an element based on its parent's sibling's child's text with Xpath

有一个这样的 html 文档:

<div class="main">
   <div class="first">
         **<div id="my_target"></div>**
    </div>
    <div class="second">
       <p class="child">I need to find  preceding or nearest sibling's child with id=my_target based on this text</p>
       <div>...</div>
        <div/>
    <div>....</div>
   </div>

谁能帮我找到一个带有 id=my_target 且具有 parent 的元素,其兄弟元素的 child 元素 p 包含一些使用 XPath 的特定文本?

按照您的解释一步步进行:

//div[@id="my_target" and ../following-sibling::div/p="some text"]

演示(使用 xmllint):

$ cat test.html
<div class="main">
   <div class="first">
         <div id="my_target">This is what I want to find</div>
    </div>
    <div class="second">
       <p class="child">some text</p>
       <div>...</div>
    </div>
    <div>....</div>
</div>
$ xmllint test.html --xpath '//div[@id="my_target" and ../following-sibling::div/p="some text"]'
<div id="my_target">This is what I want to find</div>