2014-12-07 138 views
2

我似乎无法找到答案的主题,所以我问自己。
由于这是一个通用的问题,其答案可以适用于大多数文件,我认为具体的代码示例是没有必要的。XPath - 选择不包含元素的元素

使用XPath我想选择所有不嵌套其他表的节点。
所以没有其他的后代表元素,我也想放弃所有只有空格作为它们的值的表。

我已经试过这样:

//table[not(child::table) and normalize-space(.)] 

,但它不工作。

什么是正确的做法?

谢谢。

回答

1

假设你刮(X)HTML,并注意到table不能将另一个表作为直接子元素,很可能是您正在查找descendent表元素,而不是直接child元素。

table[not(descendant::table)] 

在下面的XML:

<xml> 
    <table id="hasDescendent"> 
     <tr> 
      <td> 
       <table id="Inner Descendent"/> 
      </td> 
     </tr> 
    </table> 
    <table id="directChild"> 
     <table id="Inner Direct Child" /> 
    </table> 
    <table id="nochild"> 
    </table> 
</xml> 

//table[not(descendant::table)]返回以下table S中的XPath:

  • 内递减
  • 内直接子
  • nochild
+1

它正在工作。你是对的。后代表是正在搜索的内容。谢谢! – 2014-12-07 07:22:51

1

让我们用下面的HTML片段为例:

<div> 
    <table id="1"> 

    </table> 

    <table id="2"> 
     <table> 
      <tr> 
       <td>2</td> 
      </tr> 
     </table> 
    </table> 

    <table id="3"> 
     <div>I'm the one you wanted to find</div> 
    </table> 
</div> 

根据你的描述,第一table应该被丢弃,因为它仅包含空格,第二table也应丢弃,因为有另一个里面有table

以下XPath表达式将匹配第三table只:(使用xmllint工具)

/div/table[(not(child::table) and normalize-space(.))] 

演示:

$ xmllint index.html --xpath '/div/table[(not(child::table) and normalize-space(.))]' 
<table id="3"> 
    <div>I'm the one you wanted to find</div> 
</table> 
+0

StuartLC是对的,我提出了错误的问题。问题应该说“不包含后代表”而不是“子表”。尽管您的解决方案适用于空表格。谢谢。 – 2014-12-07 07:28:55