例如,我得到的HTML字符串像这里面的文字:使用XPath获取父节点
<p><br><a href=\"http://www.hello.com/en/\">www.hello.com</a></p>
,我希望得到的结果是这样的:
<br><a href=\"http://www.hello.com/en/\">www.hello.com</a>
但我终于在使用XPath语句时获得“www.hello.com”
//p/text()
有什么想法?
例如,我得到的HTML字符串像这里面的文字:使用XPath获取父节点
<p><br><a href=\"http://www.hello.com/en/\">www.hello.com</a></p>
,我希望得到的结果是这样的:
<br><a href=\"http://www.hello.com/en/\">www.hello.com</a>
但我终于在使用XPath语句时获得“www.hello.com”
//p/text()
有什么想法?
使用此:
//p
它wiil选择p
元素。
/p/*
将检索所有元素为p的子元素。这就是你想要的。
警告。您的元素<br>
结构不正确。你应该关闭它,因此它可以是一个很好形成空元素<br/>
/p/node() return the the same result "www.hello.com" – MaS
I don't know what XPath engine you are using. But if you do xmllint --xpath '/p/node()' file.xml - with file.xml containing your line - the ouptut is
www.hello.com。我在发布前验证它。 –
Spredzy
你如何运行XPath查询? – Spredzy
But I finally get "www.hello.com" when using the the XPath statement
//p/text()
这将选择任何文本节点是文档中的p
元素的子元素。
但是,您不仅需要文本节点的子节点,还需要任何子节点,包括元素,如<br>
和<a>
。
解:
使用:
/p/node()
当这个XPath表达式与提供的XML评价(校正为进行良好的XML文档):
<p><br/><a href="http://www.hello.com/en/">www.hello.com</a></p>
选择以下两个节点:
<br/><a href="http://www.hello.com/en/">www.hello.com</a>
XSLT - 基于验证:
这种变换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/p/node()"/>
</xsl:template>
</xsl:stylesheet>
当所提供的XML文档施加:
<p><br/><a href="http://www.hello.com/en/">www.hello.com</a></p>
将选定节点复制到输出:
<br/><a href="http://www.hello.com/en/">www.hello.com</a>
结果仍为“www.hello。com“与”// p“,我希望结果字符串中的
和节点 – MaS
@MaS,这取决于您在XPath引擎中如何使用它 –
@MaS,'// p'将选择任何p元素在文档中 –