Home > front end >  Sort xml nodes in particular order
Sort xml nodes in particular order

Time:01-11

I am not very good in xslt, following is my xslt

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*" />
<xsl:template match="printJob">
    <xsl:copy>
        <xsl:apply-templates select="printDoc[@type!='adhoc']" />
        <xsl:apply-templates select="printDoc[@type='adhoc']">
        
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

The basic purpose of my xslt is transform my xml such that all printdoc element with attribute @Type='adhoc' should be last in their parent(printJob) list, all other element should retrieve their existing order.

My current xslt is working fine, when my all my printDoc elements contains "Type" attribute, but in some xml, "Type" attribute is missing for "printDoc" element.

CodePudding user response:

If you are using XSLT 2 indeed, as your version in the code suggests, then I think the literal implementation of your requirement would be to simply use

<xsl:apply-templates select="* except printDoc[@type='adhoc'], printDoc[@type='adhoc']"/>

Run with {system-property('xsl:product-name')} {system-property('xsl:product-version')} {system-property('Q{http://saxon.sf.net/}platform')} &input= &input-type=XML" rel="nofollow noreferrer">XSLT 3 sample (could replace xsl:mode declaration with your identity template for XSLT 2).

For XSLT 1 I would use

<xsl:apply-templates select="*[not(self::printDoc[@type='adhoc'])]"/>
<xsl:apply-templates select="printDoc[@type='adhoc']"/>
  • Related