如何根据父母的兄弟姐妹的Xpath文本找到一个元素

时间:2015-01-11 03:46:33

标签: c# html 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的元素,并且父母的兄弟的子元素p包含一些使用XPath的特定文本吗?

1 个答案:

答案 0 :(得分:2)

逐步解释:

//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>