【问题标题】:Problem in sorting xml in XSLT 2.0 any ideas?在 XSLT 2.0 中排序 xml 的问题有什么想法吗?
【发布时间】:2010-02-08 15:46:59
【问题描述】:

您好,我正在尝试按元素 'answer' 与属性 'id' 的出现次数对我的 xml 进行排序并获得简单的摘要。

<person id="1">
 <answer id="A"/>
 <answer id="B"/>
</person>

<person id="2">
 <answer id="A"/>
 <answer id="C"/>
</person>

<person id="3">
 <answer id="C"/>
</person>

我想要简单的输出摘要文本:

A = 2 次
C = 2 次
B = 1 次

在 XSLT 2.0 中我尝试过:

<xsl:for-each select="distinct-values(/person/answer)">
 <xsl:sort select="count(/person/answer)" data-type="number"/>
 <xsl:value-of select="./@id"/> = 
 <xsl:value-of select="count(/person/answer[@id=./@id])"/> time(s)
</xsl:for-each>

但它不起作用:
在 XMLSpy 2008 中:
“XPath 2.0 表达式中的错误不是节点项”

在 Saxon 9 中:
XPTY0020:前导 '/' 无法选择包含上下文项的树的根节点:上下文项是原子值
无法编译样式表。检测到 1 个错误。

【问题讨论】:

    标签: sorting count xslt-2.0


    【解决方案1】:

    我会对每个组中的项目进行分组和计数:

    <xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="2.0">
    
      <xsl:output method="text"/>
    
      <xsl:template match="/">
        <xsl:for-each-group select="//person/answer" group-by="@id">
          <xsl:sort select="count(current-group())" order="descending"/>
          <xsl:value-of select="concat(current-grouping-key(), ' = ', count(current-group()), ' time(s).&#10;')"/>
        </xsl:for-each-group>
      </xsl:template>
    
    </xsl:stylesheet>
    

    这样,当应用于输入时

    <root>
    <person id="1">
     <answer id="A"/>
     <answer id="B"/>
    </person>
    
    <person id="2">
     <answer id="A"/>
     <answer id="C"/>
    </person>
    
    <person id="3">
     <answer id="C"/>
    </person>
    </root>
    

    我得到结果

    A = 2 time(s).
    C = 2 time(s).
    B = 1 time(s).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多