Xpath在需要标记之前的第一个文本

时间:2013-11-12 14:43:06

标签: html xpath

我有一些HTML代码:

<dl>
    <div>
       <div>foo</div>
    <div>
    "I need getting only this text"
    <dd>
       <div>foo</div>
       <div>foo</div>
    </dd>
    <div>
        <div>foo</div>
    <div>
    "I need getting only this text"
    <dd>
        <div>foo</div>
        <div>foo</div>
    </dd>
</dl>

所以我需要只有之前的第一个文本(不是“foo”)。 我试过像

这样的语法
  

// text()[(前面:: dd)] [某个整数]

  

//文本()[(前述:: DD)] [最后()]

但现在一切都在为我工作,因为 div 的计数与“foo” - 未定义。 我需要一些xpath,比如// dl / text(),但返回'dl'的直接祖先,没有更深层次的。

1 个答案:

答案 0 :(得分:4)

  

所以我只需要在必需的标签之前获得第一个文本

这个怎么样:

//dd/preceding-sibling::text()[1]

即。找到dd标签,然后为每个标签取最近的前一个兄弟文本节点。给出您的示例,这将返回一组两个文本节点,每个节点包含文本

'
    "I need getting only this text"
    '

(没有单引号,即换行符,四个空格,双引号,我只需要获取此文本,双引号,换行符,四个空格)。

相关问题