XML and XSLT: only specific child nodes need to be sorted

I need my XSLT stylesheet to sort my child nodes of the XML file, but only some of them. Here is an example of what XML looks like:

<?xml version="1.0"?>
<xmltop>
<child1 num="1">
<data>12345</data>
</child1>

<child1 num="2">
<data>12345</data>
</child1>

<child2 num="3">
<data>12345</data>
</child2>

<child2 num="2">
<data>12345</data>
</child2>

<child2 num="1">
<data>12345</data>
</child2>
</xmltop>

And this is the XSL file I'm using:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/xmltop">
 <xsl:copy>
  <xsl:apply-templates>
   <xsl:sort select="@num"/>
  </xsl:apply-templates>
 </xsl:copy>
</xsl:template>
<xsl:template match="child2">
 <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

This creates problems for me because the nodes are deprived of their tags and their contents remain, which makes my XML invalid. I'm not really an expert in XSL, so forgive me if this is a stupid question.

<child2> sorted correctly.

Thank.

+3
source share
1 answer

It is not determined what the result should be, so this is just me in the "guessing" mode:

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

 <xsl:template match="xmltop">
  <xsl:copy>
    <xsl:apply-templates>
      <xsl:sort select="(name() = 'child2')*@num"
       data-type="number"/>
    </xsl:apply-templates>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

When this conversion is applied to the provided XML document :

<xmltop>
    <child1 num="1">
        <data>12345</data>
    </child1>
    <child1 num="2">
        <data>12345</data>
    </child1>
    <child2 num="3">
        <data>12345</data>
    </child2>
    <child2 num="2">
        <data>12345</data>
    </child2>
    <child2 num="1">
        <data>12345</data>
    </child2>
</xmltop>

( ) :

<xmltop>
   <child1 num="1">
      <data>12345</data>
   </child1>
   <child1 num="2">
      <data>12345</data>
   </child1>
   <child2 num="1">
      <data>12345</data>
   </child2>
   <child2 num="2">
      <data>12345</data>
   </child2>
   <child2 num="3">
      <data>12345</data>
   </child2>
</xmltop>
+2

Source: https://habr.com/ru/post/1746494/


All Articles