If you already have xml and you need to generate xml, xsl may be the
easiest route. Here's a sample xml file and the transform to sort by
order id, and by quantity.
(Data.xml)
<?xml version="1.0" encoding="utf-8" ?>
<orders>
<order id="789">
<items>
<item>
<name>paint</name>
<price>2</price>
<quantity>30</quantity>
</item>
<item>
<name>glue</name>
<price>10</price>
<quantity>2</quantity>
</item>
</items>
</order>
<order id="123">
<items>
<item>
<name>sprockets</name>
<price>1</price>
<quantity>50</quantity>
</item>
<item>
<name>cogs</name>
<price>20</price>
<quantity>5</quantity>
</item>
</items>
</order>
<order id="456">
<items>
<item>
<name>nails</name>
<price>2</price>
<quantity>100</quantity>
</item>
</items>
</order>
</orders>
(Sort.xsl)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="
http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl
utput method="xml" indent="yes"/>
<xsl:template match="orders">
<orders>
<xsl:for-each select="order">
<xsl:sort data-type="number" select="@id" />
<order>
<xsl:attribute name="id">
<xsl:value-of select="@id"></xsl:value-of></xsl:attribute>
<xsl:apply-templates select="items" />
</order>
</xsl:for-each>
</orders>
</xsl:template>
<xsl:template match="items">
<xsl:for-each select="item">
<xsl:sort data-type="text" select="name" />
<item>
<name><xsl:value-of select="name"/></name>
<price><xsl:value-of select="price" /></price>
<quantity><xsl:value-of select="quantity" /></quantity>
</item>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
You can use an XSLCompiledTransform to do the sort, like this (sorry
for the C#):
static void Main(string[] args)
{
XmlTextReader xmlSource = new XmlTextReader("Data.xml");
XPathDocument xpathDoc = new XPathDocument(xmlSource);
XmlTextReader xslSource = new XmlTextReader("Sort.xsl");
XslCompiledTransform xsltDoc = new XslCompiledTransform();
xsltDoc.Load(xslSource);
StringBuilder sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);
xsltDoc.Transform(xpathDoc, null, tw);
Console.WriteLine(sb.ToString());
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
If you have other differences between your source and destination
schema you can transform it in this step too.
-Carl