首页 > 解决方案 > 使用 XSLT 对 XML 中的一个元素进行分组

问题描述

我正在尝试基于 XML 中的单个元素“h_order_num”进行分组。

原始 XML 看起来像这样

<?xml version="1.0" encoding="UTF-8"?>
<saphana>
   <row>
      <h_brand_code>DDH</h_brand_code>
      <h_brand_country>USA</h_brand_country>
      <h_order_num>0400000631</h_order_num>
   </row>
   <row>
      <h_brand_code>DDF</h_brand_code>
      <h_brand_country>France</h_brand_country>
      <h_order_num>0400000631</h_order_num>
   </row>
   <row>
      <h_brand_code>DDG</h_brand_code>
      <h_brand_country>Germany</h_brand_country>
      <h_order_num>0400000634</h_order_num>
   </row>
</saphana>

这就是我想要实现的目标

<?xml version="1.0" encoding="UTF-8"?>
<saphana>
   <row>
      <Ordernumber>
         <Value>0400000631</Value>
         <LineItems>
            <h_brand_code>DDH</h_brand_code>
            <h_brand_country>USA</h_brand_country>
         </LineItems>
         <LineItems>
            <h_brand_code>DDF</h_brand_code>
            <h_brand_country>France</h_brand_country>
         </LineItems>
      </Ordernumber>
   </row>
   <row>
      <Ordernumber>
         <Value>0400000634</Value>
         <LineItems>
            <h_brand_code>DDG</h_brand_code>
            <h_brand_country>Gernamy</h_brand_country>
         </LineItems>
      </Ordernumber>
   </row>
</saphana>

请帮我为这个转换写一个 xslt

标签: xmlxsltgrouping

解决方案


**Please Check 2.0**

        <xsl:template match="saphana">
        <xsl:copy>
            <xsl:for-each-group select="row" group-by="h_order_num">
                <xsl:copy>
                    <Ordernumber>
                        <Value>
                            <xsl:value-of select="current-grouping-key()"/>
                        </Value>
                        <xsl:for-each select=" current-group()">
                            <LineItems>
                                <h_brand_code><xsl:value-of select="child::h_brand_code"/></h_brand_code>
                                <h_brand_country><xsl:value-of select="child::h_brand_country"/></h_brand_country>
                            </LineItems>
                        </xsl:for-each>
                    </Ordernumber>
                </xsl:copy>
            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

推荐阅读