【问题标题】:XSLT add attribute value based on another valueXSLT 基于另一个值添加属性值
【发布时间】:2014-01-08 03:36:38
【问题描述】:

如何根据另一个值添加值?

<?xml version="1.0" encoding="UTF-8"?>
<items>
   <item id="A1" quantity="5">
      <info type="ram x1" import="CA" />
   </item>
   <item id="A2" quantity="3">
      <info type="ram x1" import="SA" />
   </item>
   <item id="A3" quantity="10">
      <info type="ram x2" import="AU" />
   </item>
</items>

我需要根据type 添加所有数量,例如我需要输出为,

内存 x1 数量=8 ram x2 数量=10

<?xml version="1.0" encoding="UTF-8"?>
<items>
        <details type="ram x1" quantity="8"/>
        <details type="ram x2" quantity="10"/>
</items>

尝试为每个组先获取数量,看看是否有效,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output method="html" indent="yes" />
   <xsl:template match="items">
      <xsl:for-each-group select="item" group-by="info/@type">
         <xsl:value-of select="sum(@quantity)" />
      </xsl:for-each-group>
   </xsl:template>
</xsl:stylesheet>

【问题讨论】:

    标签: xml xslt xpath xslt-2.0


    【解决方案1】:

    使用current-group()函数,即:

    <xsl:value-of select="sum(current-group()/@quantity)" />
    

    【讨论】:

      【解决方案2】:

      @Kirill Polishchuck 已经给出了很好的答案,我想添加一个完整的样式表来说明这一点。

      它以您所展示的方式输出 XML 格式。除了使用current-group(),还有一个有趣的current-grouping-key() 应用程序,它检索导致当前项目组合在一起的值。

      您已将 xsl:output method 指定为 HTML,但您的预期输出看起来像 XML。因此,我将其更改为输出 XML。

      样式表

      <?xml version="1.0" encoding="UTF-8"?>
      
      <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
      
       <xsl:output method="xml" indent="yes" />
      
       <xsl:template match="items">
        <xsl:copy>
           <xsl:for-each-group select="item" group-by="info/@type">
              <details>
                 <xsl:attribute name="type">
                    <xsl:value-of select="current-grouping-key()"/>
                 </xsl:attribute>
                 <xsl:attribute name="quantity">
                    <xsl:value-of select="sum(current-group()/@quantity)" />
                 </xsl:attribute>
              </details>
           </xsl:for-each-group>
        </xsl:copy>
       </xsl:template>
      
      </xsl:stylesheet>
      

      输出

      <?xml version="1.0" encoding="UTF-8"?>
      <items>
        <details type="ram x1" quantity="8"/>
        <details type="ram x2" quantity="10"/>
      </items>
      

      更简洁(但更复杂)的版本使用所谓的属性值模板:

      <xsl:for-each-group select="item" group-by="info/@type">
         <details type="{current-grouping-key()}" quantity="{sum(current-group()/@quantity)}"/>
      </xsl:for-each-group>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-19
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多