我似乎無法找到答案的主題,所以我問自己。
由於這是一個通用的問題,其答案可以適用於大多數文件,我認爲具體的代碼示例是沒有必要的。XPath - 選擇不包含元素的元素
使用XPath我想選擇所有不嵌套其他表的節點。
所以沒有其他的後代表元素,我也想放棄所有隻有空格作爲它們的值的表。
我已經試過這樣:
//table[not(child::table) and normalize-space(.)]
,但它不工作。
什麼是正確的做法?
謝謝。
我似乎無法找到答案的主題,所以我問自己。
由於這是一個通用的問題,其答案可以適用於大多數文件,我認爲具體的代碼示例是沒有必要的。XPath - 選擇不包含元素的元素
使用XPath我想選擇所有不嵌套其他表的節點。
所以沒有其他的後代表元素,我也想放棄所有隻有空格作爲它們的值的表。
我已經試過這樣:
//table[not(child::table) and normalize-space(.)]
,但它不工作。
什麼是正確的做法?
謝謝。
假設你刮(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:
讓我們用下面的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>
StuartLC是對的,我提出了錯誤的問題。問題應該說「不包含後代表」而不是「子表」。儘管您的解決方案適用於空表格。謝謝。 – 2014-12-07 07:28:55
它正在工作。你是對的。後代表是正在搜索的內容。謝謝! – 2014-12-07 07:22:51