使用XSLT从平面XML创建嵌套XML

时间:2019-07-02 15:43:50

标签: xml xslt xpath

我有一个以下XML文件(我不控制):

<recordset>
<row>
  <field name="orderid">1</field>
  <field name="orderlineid">1</field>
  <field name="quantity">2</field>
  <field name="item">Thing 1</field>
</row>
<row>
  <field name="orderid">2</field>
  <field name="orderlineid">2</field>
  <field name="quantity">1</field>
  <field name="item">Thing 3</field>
</row>
<row>
  <field name="orderid">2</field>
  <field name="orderlineid">3</field>
  <field name="quantity">1</field>
  <field name="item">Thing 2</field>
</row>
<row>
  <field name="orderid">3</field>
  <field name="orderlineid">4</field>
  <field name="quantity">3</field>
  <field name="item">Other</field>
</row>
</recordset>

我正在与XSLTfor-each-group努力按订单ID分组并生成以下XML:


                                                                         

到目前为止,我的出席情况是

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:key name="keyOrder" match="row" use="field/@name = 'COMMANDE'" />
    <xsl:template match="resultset">
    <commandes xmlns:od="http://www.w3.org/2001/XMLSchema-instance">
            <xsl:apply-templates/>
    </commandes>
    </xsl:template>
    <xsl:template match="row">
        <orders>    
            <xsl:for-each-group select="./child::*" group-by="field/@name = 'orderid'">
                <order>
                    <xsl:value-of select="field[@name = 'COMMANDE']"/>
                </order>
            </xsl:for-each-group>
        </orders>
    </xsl:template> 
</xsl:stylesheet>

我如何: -基于子节点进行分组 -计算每组中有多少行?

1 个答案:

答案 0 :(得分:1)

考虑从定义jQuery开始的Muenchian Grouping

<xsl:key>

XSLT Fiddle Demo

输出

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="keyOrder" match="row" use="field[@name='orderid']"/>

    <xsl:template match="recordset">
        <commandes xmlns:od="http://www.w3.org/2001/XMLSchema-instance">
            <xsl:apply-templates select="row[generate-id() =
                        generate-id(key('keyOrder', field[@name='orderid'])[1])]"/>
        </commandes>
    </xsl:template>

    <xsl:template match="row">
        <order id = "{field[@name='orderid']}" 
               lines = "{count(. | key('keyOrder', field[@name='orderid']))}"> 

                <xsl:for-each select="key('keyOrder', field[@name='orderid'])">
                    <orderline id = "{field[@name='orderlineid']}" 
                               quantity = "{field[@name='quantity']}"
                               item = "{field[@name='item']}" />
                </xsl:for-each>

        </order>
    </xsl:template> 

</xsl:stylesheet>