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

Paul is the COO of kwiboo ltd and has more than 20 years 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.

Comments

ricardo said:

Can you give me some hits about using your code to sort this xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<campos>

  <ComboBox indice="4">
    <nome>nome</nome>
    <conn>Server</conn>
    <tipo>sqlserver</tipo>
    <sql>SELECT</sql>
    <descricao>Nome do Utilizador</descricao>
  </ComboBox>
  <Data indice="1">
    <nome>dataDigi</nome>
    <descricao>Data DigitalizaĆ§Ć£o</descricao>
  </Data>
  <config>
    <repositorio>c:\rep\</repositorio>
  </config>
  <ComboBox2 indice="3">
    <nome>TipoEntidade</nome>
    <descricao>Tipo Entidade</descricao>
    <campos>
      <campo>Cliente</campo>
      <campo>Fornecedor</campo>
    </campos>
  </ComboBox2>
  <ComboBox3 indice="2">
    <nome>combo1</nome>
    <descricao>descricao1</descricao>
    <nome2>combo2</nome2>
    <descricao2>descricao2</descricao2>
    <tipo>combobox</tipo>
    <campos>
      <campo>
        <id>clientes</id>
        <conn>Server</conn>
        <tipoBD>sqlserver</tipoBD>
        <sql>SELECT</sql>
      </campo>
      <campo>
        <id>fornecedores</id>
        <conn>Provider</conn>
        <tipoBD>access</tipoBD>
        <sql>SELECT</sql>
      </campo>
    </campos>
  </ComboBox3>
  <ComboBox indice="0">
    <nome>formandos</nome>
    <conn>Server</conn>
    <tipo>sqlserver</tipo>
    <sql>SELECT</sql>
    <descricao>Formandos</descricao>
  </ComboBox>

</campos>

Thanks!

10/Aug/2007 12:20 PM

phayman said:

How would you like to sort it?

10/Aug/2007 13:09 PM

Francisco said:

Thank you very much, your code really helped me!

31/Oct/2008 23:00 PM

ghulam Haider said:

What is successes? C# gives error that is is not defined. Please help me. I need you code urgently.

28/Nov/2008 09:23 AM

phayman said:

successes is the root node of my XML document

<successes>

28/Nov/2008 11:19 AM

Ghulam Haider said:

Thank you very much for you shortest code. I could not run your code till my PM help me and run your code after some amendments. Sorry I am new to XML. Again thanks for your response. This is our xml file <?xml version="1.0" encoding="utf-8" ?>

<videos>

  <video name="name1" url="url1" id="1">
    <thumb>thumb1</thumb>
    <description>description1</description>
  </video>

</videos>

// 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);


        XPathDocument myXPathDocument = new XPathDocument(Server.MapPath(@"~/XMLFile.xml"));


        XslCompiledTransform sortXsl = new XslCompiledTransform();
        sortXsl.Load(Server.MapPath(@"~/XSLTFile.xsl"));
        sortXsl.Transform(myXPathDocument, writer);
        writer.Close();


        XmlDocument xmlDoc = new XmlDocument();


        xmlDoc.LoadXml(sortedXml.ToString());


        Label1.Text = sortedXml.ToString();
29/Nov/2008 07:49 AM

eMan said:

sortXsl.Transform(successes, writer);

What is 'successes' here. I mean, what is its datatype. Is it a XmlDocument??

05/Feb/2009 07:03 AM

eMan said:

hai Paul

 sortXsl.Transform(successes, writer);

Here what is the datatype of "successes". Is it a SYstem.Xml.XmlDocument

Regards

10/Feb/2009 05:07 AM

ibrucken said:

Hello Paul

Very usefull sample for me.

Could you tell me how to do the sort by attribute instead of node?

Thank you.

25/Feb/2009 20:43 PM

phayman said:

Try:

<xsl:sort select="@yourattribute" data-type="number" order="descending"/>

23/Mar/2009 10:33 AM

Paco Marquez said:

Great example man, this help me a lot!

Thanks!

10/Aug/2010 23:12 PM

Kenny DellaValle said:

This post was extremely helpful, thanks for the post!

15/Feb/2011 03:05 AM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.