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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort XML File Output as XML

Status
Not open for further replies.

Jakos23

Programmer
Mar 17, 2005
5
GB
Can anyone tell me where I'm going wrong, what I'm trying to do is sort the following xml file, by the <start> element and output the data as xml.

XML FILE:


Code:
<?xml-stylesheet type="xml" href="sort.xsl"?>
<markers>
<book ID="War of the Worlds">
    <highlights>
        <highlight> 
            <start>2001</start>
            <end>2005</end>
        </highlight>
        <highlight>
            <start>2380</start>
            <end>2410</end>
        </highlight>
        <highlight>
            <start>10</start>
            <end>32</end>
        </highlight>
    </highlights>
</book>
<book ID="Help">
    <highlights>
        <highlight>
            <start>12</start>
            <end>30</end>
        </highlight>
        <highlight>
            <start>2</start>
            <end>6</end>
        </highlight>
    </highlights>
</book>
</markers>

using the following xsl style sheet


Code:
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/xsl/transform">[/URL]
<xsl:output method="xml" version="1.0"
encoding="utf-8"/>
<xsl:template match="markers/book/highlights">


<xsl:for-each select="highlight">
<xsl:sort select="start"
data-type="number"
order="ascending"/>
<xsl:value-of select="start"/>
</xsl:for-each>


</xsl:template>
</xsl:stylesheet>
 
There's a few problems with the code. It's trying to output the value of the node rather than copying the node itself. Also, it only matches the highlight nodes, therefore knows nothing about the ancestors. Try:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform">[/URL]
  <xsl:output method="xml" version="1.0" encoding="utf-8"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="highlights">
    <highlights>
      <xsl:for-each select="highlight">
        <xsl:sort select="start" data-type="number" order="ascending"/>
        <xsl:copy-of select="."/>
      </xsl:for-each>
    </highlights>
  </xsl:template>
</xsl:stylesheet>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top