使用:
/*/tr[2]/td[2]/p/span/text()
當這個XPath表達式與下面的XML文檔(通過轉動提供不良HTML成簡潔(wellformed)XML文檔而獲得)來評價:
<table>
<tr>
<td>
<p>
<span>text</span>
</p>
</td>
<td>
<p>
<span>text</span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<span>Some text</span>
</p>
</td>
<td>
<p>
<span>text to extract</span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<span>text</span>
</p>
</td>
<td>
<p>
<span>text</span>
</p>
</td>
</tr>
</table>
的根據需要選擇值爲"text to extract"
的文本節點。
XSLT - 基於驗證:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
"<xsl:copy-of select="/*/tr[2]/td[2]/p/span/text()"/>"
</xsl:template>
</xsl:stylesheet>
當該變換是在相同的XML文檔(上文),XPath表達式求值和該評價的結果施加被複制到輸出 :
"text to extract"
或者,如果你知道的文字,但要選擇包含的一個元素(比如td
),然後使用:
//text()[. = 'text to extract']/ancestor::td[1]
再次用基於XSLT的驗證:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy-of select=
"//text()[. = 'text to extract']/ancestor::td[1]"/>
</xsl:template>
</xsl:stylesheet>
結果現在是:
<td>
<p>
<span>text to extract</span>
</p>
</td>
又一猜:
如果你想找到最接近前文本節點,然後用:
//text()[. = 'text to extract']/preceding::text()[1]
XSLT - 基於驗證:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
"<xsl:copy-of select=
"//text()[. = 'text to extract']/preceding::text()[1]"/>"
</xsl:template>
</xsl:stylesheet>
結果:
"Some text"
更新:
由OP,和他的新解釋,XPath表達式,他正在尋找最新的更新後:
//text()[. = 'This text is static and will never change']/following::text()[1]
這將選擇與字符串值的文本節點:
"Bla bla bla .... more bla bla bla"
使用的是什麼語言 - PHP? JavaScript的? HTML本身不能做到這一點。請編輯問題以標記語言。 – Utkanos 2012-08-05 21:59:24
@Utkanos:XPath表達式與語言無關。 – 2012-08-05 22:00:28
我意識到這一點,但他/她將用某種語言來實現它。他/她被重新標記爲C#。 – Utkanos 2012-08-05 22:04:08