首页 文章

xpath查找节点是否存在

提问于
浏览
190

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

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

6 回答

  • 3
    <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>
    
  • 68

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

  • 2

    Patrick在使用 xsl:if 时都是正确的,并且在检查节点存在的语法中是正确的 . 然而,正如帕特里克's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you'通常更好地使用 xsl:choosexsl:otherwise . 因此,Patrick的示例语法将起作用,但这是另一种选择:

    <xsl:choose>
     <xsl:when test="/html/body">body node exists</xsl:when>
     <xsl:otherwise>body node missing</xsl:otherwise>
    </xsl:choose>
    
  • 12

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

    我经常使用 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>
    
  • 300

    我在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?
    
  • 44

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

    int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
    if( numberofbodies==0) {
        // body node missing
    }
    

相关问题