首页 文章

如何使用xPath 1.0检查id引用是否有效?

提问于
浏览
0

我是xml,xsl和xPath的初学者 . 我想知道如何检查我的所有refid属性是否有效?

换句话说,如果每个refid属性都具有匹配的ID属性(当然具有相同的值),我希望有一个xPath 1.0查询返回TRUE . 所有产品都没有必要的ref节点 .

例如:如果cookie指向面包和面包指向牛奶和牛奶poist到cookie那么返回TRUE,否则为FALSE .

我一直试图解决这个问题,并在没有运气的情况下搜索网络 . 非常感谢帮助!

这是我的XML:

<shop>
 <product>
    <cookie ID="01">
    <price>2</price>
    </cookie>
    <ref refid="02"/>
 </product>

  <product>
    <bread ID="02">
    <price>5</price>
    </bread>
    <ref refid="03"/>
 </product>

 <product>
   <milk ID="03">
   <price>2</price>
   </milk>
   <ref refid="01"/>
</product>

</shop>

3 回答

  • 1

    你可以使用 boolean() . 以下将返回 truefalse

    boolean(not(//@refid[not(.=//@ID)]))
    

    XSLT示例:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output indent="yes"/>
        <xsl:strip-space elements="*"/>
    
        <xsl:template match="/">
            <xsl:value-of select="boolean(not(//@refid[not(.=//@ID)]))"/>
        </xsl:template>
    
    </xsl:stylesheet>
    

    boolean() 也可用于Martin更高效 xsl:key 版本:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output indent="yes"/>
        <xsl:strip-space elements="*"/>
    
        <xsl:key name="id" match="product" use="*[1]/@ID"/>
    
        <xsl:template match="/">
            <xsl:value-of select="boolean(not(//ref[not(key('id', @refid))]))"/>
        </xsl:template>
    
    </xsl:stylesheet>
    
  • 1

    找到所有没有匹配 @id@refid 属性 .

    //@refid[not(//@ID = .)]
    

    如果计算结果并将其与零进行比较,则对于有效输入将返回 true ,对于已损坏的引用将返回 false .

    count(//@refid[not(//@ID = .)]) = 0
    
  • 0

    问题被标记为 xslt 以及 xpath 我敢于使用密钥建议XSLT 1.0方法:

    <xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="1.0">
    
    <xsl:key name="id" match="product" use="*[1]/@ID"/>
    
    <xsl:template match="/">
      <xsl:choose>
        <xsl:when test="//ref[not(key('id', @refid))]">FALSE</xsl:when>
        <xsl:otherwise>TRUE</xsl:otherwise>
      </xsl:choose>
    </xsl:template>
    
    </xsl:stylesheet>
    

相关问题