filipv
filipv

Reputation: 324

XML element ordering by inner element with XSLT transformation

Say I have the following XML and I want XSLT transformation which would change the ordering of <invoice> elements by the value of <paymentType> element. How should the XSLT look like?

Input:

<invoices>
  <invoice>
    <paymentType>
      1
    </paymentType>
  </invoice>
  <invoice>
    <paymentType>
      2
    </paymentType>
  </invoice>
  <invoice>
    <paymentType>
      1
    </paymentType>
  </invoice>
</invoices>

Desired output:

<invoices>
  <invoice>
    <paymentType>
      1
    </paymentType>
  </invoice>
  <invoice>
    <paymentType>
      1
    </paymentType>
  </invoice>
  <invoice>
    <paymentType>
      2
    </paymentType>
  </invoice>
</invoices>

EDIT: As suggest I am providing my current XSLT, which also includes the solution from marked answer in this thread. Any suggestions for improvement are welcome.

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
<xsl:template match="/invoices">
    <xsl:copy>
        <xsl:apply-templates select="invoice">
            <xsl:sort select="paymentType" data-type="number" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template> 
</xsl:stylesheet>

Upvotes: 0

Views: 84

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

<xsl:template match="/invoices">
    <xsl:copy>
        <xsl:apply-templates select="invoice">
            <xsl:sort select="paymentType" data-type="number" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template> 

Hopefully you know the rest.

Upvotes: 1

Related Questions