使用 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
和 xsl:otherwise
。因此,Patrick 的示例语法将起作用,但这是另一种选择:
<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"
放在第二个什么时候使它成为 if-else if-else
?
使用选项可能会更好,不必多次输入(或可能错误输入)您的表达式,并允许您遵循其他不同的行为。
我经常使用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>
count(/html/body) = 0
天才! :DI 将其用作 /html[count(/body)=0]/someNode
以在缺少 /body
(或其他)时选择 someNode
/html[count(/body)=0]
永远不会选择任何东西,XML 中不能有两个根节点。也许您的意思是 /html[count(body)=0]
,它与 /html[not(body)]
或 /html[not(exists(body))]
相同。
我在 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
}
不定期副业成功案例分享
html/body and not(html/body/node())
(即,仅测试它是否存在并且它不包含任何子节点或文本节点)。