xpath查找节点是否存在

时间:2009-04-20 11:14:39

标签: xslt xpath expression

使用xpath查询如何查找节点(标记)是否存在?

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

6 个答案:

答案 0 :(得分:310)

<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>

答案 1 :(得分:68)

请尝试以下表达式:boolean(path-to-node)

答案 2 :(得分:47)

Patrick在使用xsl:if和检查节点存在的语法方面都是正确的。然而,正如帕特里克的回答所暗示的那样,没有xsl等同于if-then-else,所以如果你正在寻找更像if-then-else的东西,你通常最好使用xsl:choose和{{ 1}}。因此,Patrick的示例语法将起作用,但这是另一种选择:

xsl:otherwise

答案 3 :(得分: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>

答案 4 :(得分: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?

答案 5 :(得分:3)

使用count():

在Java中使用xpath时的变体
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
    // body node missing
}
相关问题