1

There is given order of nodes and I need to sort the nodes of XML according to the given order. The input is a XML file and output is the XML file with nodes ordered according to given list.

XML:

<root>
    <M node="C" home="zzz"/>
    <X name="A"/>
    <Z/>
    <Y test="B"/>    
</root>

XSLT:

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

 <xsl:param name="pSortingValues" select="'Y,X,Z,M,N'"/>
 <xsl:variable name="vSortingValues" select=
  "concat(',', $pSortingValues, ',')"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
       <xsl:apply-templates select="node()|@*">
        <xsl:sort data-type="number" select=
        "string-length(substring-before($vSortingValues,concat(',',name,',')))"/>
       </xsl:apply-templates>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Received Output:

<root>
  <M node="C" home="zzz"/>
  <X name="A"/>
  <Z/>
  <Y test="B"/>
</root>

Desired Output:

<root>
 <Y test="B"/>
 <X name="A"/>
 <Z/>
 <M node="C" home="zzz"/>        
</root>

The above XSLT currently only parses the XML without sorting in the required order of nodes: 'Y,X,Z,M,N'.

1 Answer 1

2

You are trying to sort by node name, but the expression name is looking for an element called "name". You need to use name() to get the name of the node

<xsl:sort data-type="number" select="string-length(substring-before($vSortingValues,concat(',', name(),',')))"/>

Note, for future reference, you can also use local-name() here. name() would include any namespace prefix, should namespaces be involved, whereas local-name() returns the name without any prefix.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.