user3659557
user3659557

Reputation:

Grouping elements together with two xml documents XSLT2.0

How would one group elements and then return the siblings as sub elements?

Here's a snipping of what I'm trying to achieve (This is only a snippit so in reality the code will have multiple customers, orders and types of food)

customers.xml

<customers>
  <customer>
    <fname>James</fname>
    <orderid>1234</orderid>
  </customer>      

orders.xml

<orders>
  <order>
    <orderid>1234</orderid>
    <name>soda</name>
    <size>large</size>
    <type>drink</type>
  </order>

  <order>
    <orderid>1234</orderid>
    <name>beer</name>
    <size>medium</size>
    <type>drink</type>
  </order>

  <order>
    <orderid>1234</orderid>
    <name>burger</name>
    <size>large</size>
    <type>food</type>

output.xml

<orders>
  <order>
    <fname>James</fname>
    <orderid>1234<orderid>
    <bought type="food">
      <name name="burger">
        <size>large</size>
      </name>
    </bought>
    <bought type="drink">
      <name name="soda">
        <size>large</size>
      </name>
      <name name="beer">
        <size>medium</size>
      </name>
    </bought>
  </order>
</orders>

So I want to group all the types of food together and have the names of them and size as subelements, how would I achieve this in the most simplest way possible?

Upvotes: 1

Views: 35

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167506

Well XSLT 2.0 has for-each-group e.g.

<xsl:param name="orders-url" select="'orders.xml'"/>
<xsl:variable name="orders-doc" select="doc($orders-url)"/>

<xsl:key name="orderid" match="order" use="orderid"/>

<xsl:template match="customer">
  <order>
    <xsl:copy-of select="fname, orderid"/>
    <xsl:for-each-group select="key('orderid', orderid, $orders-doc)" group-by="type">
      <bought type="{type}">
        <xsl:apply-templates select="current-group()"/>
      </bought>
    </xsl:for-each-group>
  </order>
</xsl:template>

<xsl:template match="order">
  <name name="{name}">
    <xsl:copy-of select="size"/>
  </name>
</xsl:template>

Upvotes: 1

Related Questions