208

使用 XPath 查询如何确定节点(标记)是否存在?

例如,如果我需要确保网站页面具有正确的基本结构,例如/html/body/html/head/title.

4

6 回答 6

331
<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>
于 2009-04-20T11:26:43.343 回答
76

试试下面的表达式:boolean(path-to-node)

于 2010-09-20T12:37:32.480 回答
51

Patrick 是正确的,无论是使用 ,还是xsl:if检查节点是否存在的语法。但是,正如 Patrick 的回答所暗示的那样,没有与 if-then-else 等效的 xsl,因此,如果您正在寻找更像 if-then-else 的东西,通常最好使用xsl:chooseand xsl:otherwise。因此,Patrick 的示例语法将起作用,但这是另一种选择:

<xsl:choose>
 <xsl:when test="/html/body">body node exists</xsl:when>
 <xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>
于 2011-07-04T10:38:27.313 回答
13

使用选项可能会更好,不必多次输入(或可能错误输入)您的表达式,并允许您遵循其他不同的行为。

我经常使用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>
于 2011-05-01T17:03:18.317 回答
4

我在 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?
于 2012-02-16T23:30:33.463 回答
3

使用 count() 在 Java 中使用 xpath 时的一种变体:

int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
    // body node missing
}
于 2010-04-25T12:10:39.167 回答