Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting nested elements 2

Status
Not open for further replies.

mashadt

Instructor
Apr 23, 2005
33
ZA
I want to sort nested elements without losing their placement inside their parent elements when they get displayed in the browser.

If I have an XML document something like this:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
<section order="3">

<para order = "3">
</para>
<para order = "2">
</para>
<para order = "1">
</para>

</section>

<section order="1">

<para order = "3">
</para>
<para order = "2">
</para>
<para order = "1">
</para>

</section>

<section order="2">

<para order = "3">
</para>
<para order = "2">
</para>
<para order = "1">
</para>

</section>
</notes>


I can get the "section" elements to appear in a different order by using XSLT something like this:

<xsl:template match=" /">

<xsl:apply-templates select="//section">
<xsl:sort select="@order" />
</xsl:apply-templates>

</xsl:apply-templates>


</xsl:template>

---------------------------------

If I use

<xsl:template match = "/">
<xsl:apply tempates/>

</xsl:template>

<xsl:template match="//section">

<xsl:apply-templates select="//section">
<xsl:sort select="@order" />
</xsl:apply-templates>

</xsl:apply-templates>

<xsl:template match="section">
<xsl:apply-templates select="para">
<xsl:sort select="@order" data-type="number"/>
</xsl:apply-templates>

</xsl:template>
---------------------------------------------
Then the information in the browser comes out something like this:

Section1
Section2
Section3

Para1
Para2
Para3
Para1
Para2
Para3

etc

Instead of

Section1
Para1
Para2
Para3

Section2
Para1
Para2
Para3.

But how can I get the nested "para" elemets to appear in the order suggested by their "order" attributes as well? At the moment, I can only get them to appear sorted outside of their sections. I would like the paragraphs to appear in their relevant sections.

Thanks


 
Such as this.
[tt]
<xsl:template match="notes">
<xsl:copy>
<xsl:for-each select="@*">
<xsl:copy-of select="." />
</xsl:for-each>
<xsl:for-each select="child::*">
<xsl:sort select="@order" />
<xsl:element name="{name(.)}">
<xsl:for-each select="@*">
<xsl:copy-of select="." />
</xsl:for-each>
<xsl:for-each select="child::*">
<xsl:sort select="@order" />
<xsl:copy-of select="." />
</xsl:for-each>
</xsl:element>
</xsl:for-each>
</xsl:copy>
</xsl:template>
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top