Sultan Saadat
Sultan Saadat

Reputation: 2288

Order of XML Elements Using XSLT

Suppose i have an xml document like this

XML File:

<document>
  <educationalsection>
  educational details
  </educationalsection>

  <professionalsection>
  professional section details
  </professionalsection>
</document>

I have created XSL to converge it into my required format but the problem is if i want to change the order of the sections how can i do that? For instance if i want the professional section to come on top of educational without changing the xml, how is that possible? WHat will i need to add to my existing xsl or xml so that when my web application send the xml for transformation it can have different orders of elements as specified by the web app.

Upvotes: 1

Views: 1876

Answers (2)

user357812
user357812

Reputation:

This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="pOrder" select="'professionalsection,educationalsection'"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*">
                <xsl:sort select="string-length(
                                     substring-before(
                                        concat(',',$pOrder,','),
                                        concat(',',name(),',')))"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output:

<document>
    <professionalsection>
     professional section details
    </professionalsection>
    <educationalsection>
     educational details
    </educationalsection>
</document>

Upvotes: 2

Oded
Oded

Reputation: 499352

The xsl:apply-templates and xsl:for-each elements can have xsl:sort child elements that can be used to order the child nodes that were selected. Use different sort orders whenever you need to.

You can also use the mode attribute on xsl:template to select different templates using different sort orders.

Upvotes: 1

Related Questions