如何使用XPath查找节点(标记)是否存在?
例如,如果我需要确保网站页面具有正确的基本结构,例如 /html/body
和 /html/head/title
。
如何使用XPath查找节点(标记)是否存在?
例如,如果我需要确保网站页面具有正确的基本结构,例如 /html/body
和 /html/head/title
。
<xsl:if test="xpath-expression">...</xsl:if>
例如,
<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>
html/body and not(html/body/node())
(即仅测试它是否存在并且不包含任何子节点或文本节点)。 - Abel请尝试使用以下表达式:boolean(节点路径)
帕特里克是正确的,他在使用 xsl:if
中和检查节点存在的语法方面都是正确的。然而,正如帕特里克所暗示的那样,没有xsl等同于if-then-else。因此,如果你想要类似if-then-else的操作,通常最好使用 xsl:choose
和 xsl:otherwise
。所以,帕特里克的示例语法可以工作,但这是另一种选择:
<xsl:choose>
<xsl:when test="/html/body">body node exists</xsl:when>
<xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>
if-then-else
,那么 if-else if-else
呢?在 davenpcj 的回答中,我可以将 test="somexpath"
放在第二个 when 中使其成为 if-else if-else
吗? - AabinGunz使用选择器可能更好,不必多次键入表达式(或可能出现的打字错误),并且允许您遵循其他不同的行为。
我经常使用count(/html/body) = 0
,因为节点的具体数量比集合更有趣。例如...当有意外地有超过一个与您的表达式匹配的节点时。
<xsl:choose>
<xsl:when test="/html/body">
<!-- Found the node(s) -->
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
<!-- No node exists -->
</xsl:otherwise>
</xsl:choose>
count(/html/body) = 0
太聪明啦! :D
当 /body
(或其他元素) 缺失时,我使用它作为 /html[count(/body)=0]/someNode
来选择 someNode
。 - Stefan Rogin我使用Ruby编程语言,并使用Nokogiri库获取元素,然后查看结果是否为空。
require 'nokogiri'
url = "http://somthing.com/resource"
resp = Nokogiri::XML(open(url))
first_name = resp.xpath("/movies/actors/actor[1]/first-name")
puts "first-name not found" if first_name.nil?
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
// body node missing
}