Sorting an XML document in C# using XSL
I needed to sort some XML in C# before itterating through the document. In the end I used the XslCompiledTransform to apply an XSL stylesheet to the XML document. Works very quickly. For reference, this is how I did it.
The code
The following uses an XslCompiledTransform object to apply an XSL transformation. The output is written to a StringBuilder and reloaded into the successes XML document.
// sort the successes based on priority
System.Text.StringBuilder sortedXml = new System.Text.StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
XmlWriter writer = XmlWriter.Create(sortedXml, settings);
XslCompiledTransform sortXsl = new XslCompiledTransform();
sortXsl.Load(Server.MapPath(@"~/SuccessSort.xsl"));
sortXsl.Transform(successes, writer);
writer.Close();
successes.LoadXml(sortedXml.ToString());
The XSL in my SuccessSort.xsl document
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="successes">
<successes>
<xsl:apply-templates select="success">
<xsl:sort select="priority" data-type="number" order="descending"/>
</xsl:apply-templates>
</successes>
</xsl:template>
<xsl:template match="success">
<xsl:copy-of select="." />
</xsl:template>
</xsl:stylesheet>
The XML inside my successes XmlDocument
<successes>
<success>
<priority>5</priority>
<!-- stuff -->
</success>
<success>
<priority>2</priority>
<!-- stuff -->
</success>
<success>
<priority>3</priority>
<!-- stuff -->
</success>
</successes>
| Author |
: Paul Hayman |
| Published |
: Wednesday, 20 June, 2007 |
Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.