如何使用XPath计算具有特定属性的节点数量

29

我似乎无法针对我的情况获得XPath表达式。 我想找到所有类型为“EndDevice”的“Device”节点。 我能够计算所有“Device”节点的数量,并且我也能够找到所有具有“EndDevice”属性的“Device”节点。 但是,我似乎无法将它们结合起来!

count(//Device) //works
//Device[@xsi:type='EndDevice'] //works
count(//Device[@xsi:type='EndDevice']) //doesn't work

如果有影响的话,我正在使用XPathBuilder。

第二个“有效”是什么意思? 它匹配了一些节点吗? 您的XPath看起来正确,因此要么是您未显示的代码部分出现了问题,要么是您正在使用的工具出现了问题。 - Peter Jacoby
2个回答

21

我使用XPathBuilder 2.0.0.4重现了它。 但是我尝试过的在线评估器中XPath表达式能够正常工作并正确评估(http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm)。

编辑: 还尝试了最新版本的Altova XMLspy

输入:

<?xml version="1.0"?>
<asdf xmlns:xsi="n/a">
    <Device xsi:type='EndDevice'/>
    <Device xsi:type='EndDevice'/>
    <Device xsi:type='EndDevice'/>
    <Device xsi:type='EndDevice'/>
</asdf>

xslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsi="n/a">
    <xsl:output indent="yes"/>
    <xsl:template match="*">
        <output>
            <xsl:value-of select="count(//Device[@xsi:type = 'EndDevice'])"/>
        </output>
    </xsl:template>
</xsl:stylesheet>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<output xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsi="n/a">4</output>

我认为是XPathBuilder出了问题。


1
同意。这很可能是XPathBuilder的问题。我使用Xalan、Saxon 6.5.5、Saxon HE 9.2.0.3在oXygen中测试了XML/XSLT,并得到了期望的输出。 - Mads Hansen

3

使用上述xml保存到test.xml中,并使用工具http://kernowforsaxon.sourceforge.net/

declare namespace xsi="n/a"; 
count(doc('test.xml')//Device[@xsi:type = "EndDevice"])

产生正确的输出。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接