如何计算XSLT中的引用总数?

时间:2009-04-10 04:27:17

标签: xml xslt xpath

我的问题是:使用XSLT,如何计算QUOTE标签的总数(请参阅下面的示例代码) 结果需要在HTLM中导出,它将显示如下:共有6个引号

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="text.xsl" ?>

    <quotes>
      <quote>Quote 1 </quote>
      <quote>Quote 2</quote>
      <quote>Quote 3</quote>
      <quote>Quote 4</quote>
      <quote>Quote 5</quote>
      <quote>Quote 6</quote>
    </quotes>

我已经尝试过这个XSLT代码,但它不起作用:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      exclude-result-prefixes="xs"
      version="2.0">
    <xsl:template match="/">
        <xsl:value-of select="count(//quote)"></xsl:value-of>
    </xsl:template>

</xsl:stylesheet>

请你帮我解决这个问题吗?谢谢

2 个答案:

答案 0 :(得分:3)

您的XPath表达式,虽然效率不高,会产生正确的结果

使用Saxon 9.1.0.5J运行转换时,结果为:

<?xml version="1.0" encoding="UTF-8"?>6

问题似乎是这是一个XSLT 2.0转换(它不需要!),你似乎试图在浏览器中运行它。 不幸的是,今天的浏览器不支持(尚未)XSLT 2.0

解决方案是将版本更改为1.0

此转换也不需要XML Schema名称空间。

最后,如果提供的XML文档的结构不会改变,则更高效的XPath表达式(因为使用//缩写导致从顶部元素节点开始的整个(子)树被扫描),将是以下内容:

count(/*/quote)

将所有这些放在一起我们得到以下转变

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 >
 <xsl:output method="html"/>

    <xsl:template match="/">
        <xsl:value-of select="count(/*/quote)"/>
    </xsl:template>
</xsl:stylesheet>

并产生想要的结果

答案 1 :(得分:0)

它似乎在Firefox 3和IE6中运行良好。有关您的设置的更多信息?

相关问题