Transform XML using XSLT based on element position

I

Igor

Is there any way to resort and xml document using xslt based on
element position.
For example if I have xml like this:
<root>
<element> 1st thing </element>
<element> 2nd thing </element>
<element> 3rd thing </element>
</root>

would it be possible using xslt only to reverse it into:
<root>
<element> 3rd thing </element>
<element> 2nd thing </element>
<element> 1st thing </element>
</root>

I also can't sort based on the alphabetical or numerical order of the
actual information between the element tags, only on the position of
the tags, ie I would like to reverse their order.
 
D

Dimitre Novatchev

Igor said:
Is there any way to resort and xml document using xslt based on
element position.
For example if I have xml like this:
<root>
<element> 1st thing </element>
<element> 2nd thing </element>
<element> 3rd thing </element>
</root>

would it be possible using xslt only to reverse it into:
<root>
<element> 3rd thing </element>
<element> 2nd thing </element>
<element> 1st thing </element>
</root>

Yes, this is straightforward. This transformation:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:eek:utput 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="root">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="position()"
order="descending"
data-type="number"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

when applied on your source.xml:

<root>
<element> 1st thing </element>
<element> 2nd thing </element>
<element> 3rd thing </element>
</root>

produces the wanted result:

<root>
<element> 3rd thing </element>
<element> 2nd thing </element>
<element> 1st thing </element>
</root>



I also can't sort based on the alphabetical or numerical order of the
actual information between the element tags, only on the position of
the tags, ie I would like to reverse their order.


Sorry, but I cannot understand what you mean here.


=====
Cheers,

Dimitre Novatchev.
http://fxsl.sourceforge.net/ -- the home of FXSL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top