使用 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>
试试下面的表达式:boolean(path-to-node)
Patrick 是正确的,无论是使用 ,还是xsl:if
检查节点是否存在的语法。但是,正如 Patrick 的回答所暗示的那样,没有与 if-then-else 等效的 xsl,因此,如果您正在寻找更像 if-then-else 的东西,通常最好使用xsl:choose
and xsl:otherwise
。因此,Patrick 的示例语法将起作用,但这是另一种选择:
<xsl:choose>
<xsl:when test="/html/body">body node exists</xsl:when>
<xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>
使用选项可能会更好,不必多次输入(或可能错误输入)您的表达式,并允许您遵循其他不同的行为。
我经常使用count(/html/body) = 0
,因为具体的节点数量比集合更有趣。例如...当意外超过 1 个节点与您的表达式匹配时。
<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>
我在 Ruby 中工作并使用 Nokogiri 获取元素并查看结果是否为 nil。
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?
使用 count() 在 Java 中使用 xpath 时的一种变体:
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
// body node missing
}