0

I have below Xml structure.

<Root>
<Customers>
<Customer>
<ID1>100</ID1>
<ID2>5555</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>200</ID1>
<ID2>445</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>30</ID1>
<ID2>58878</ID2>
<OtherElements />
</Customer>
<Customers>
</Root>

I would like to re-arrange Customer Nodes with ID1 ASC, AND ID2 ASC sorting Order. Please help me to achieve this without XSLT and LINQ.

Thanks

1
  • Post a well-formed XML sample to start with, currently your sample has one <Customer> start tag but several </Customer> end tags, so that is not a well-formed document. Commented Nov 27, 2013 at 15:53

1 Answer 1

3

Well the .NET framework's XPath/XSLT implementation exposes a sort feature on XPathExpression:

        XmlDocument doc = new XmlDocument();
        doc.Load("file.xml");

        XPathExpression customers = XPathExpression.Compile("/Root/Customers/Customer");
        customers.AddSort("ID1", XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, "", XmlDataType.Number);
        customers.AddSort("ID2", XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, "", XmlDataType.Number);

        XmlElement parent = doc.DocumentElement["Customers"];
        foreach (XPathNavigator cust in doc.CreateNavigator().Select(customers))
        {
            parent.AppendChild(cust.UnderlyingObject as XmlNode);
        }

        doc.Save(Console.Out); // for testing, use Save("file.xml") to save

With the input being

<?xml version="1.0" encoding="utf-8" ?> 
<Root>
<Customers>
<Customer>
<ID1>100</ID1>
<ID2>5555</ID2>
<OtherElements />
</Customer>
  <Customer>
<ID1>200</ID1>
<ID2>445</ID2>
<OtherElements />
</Customer>
  <Customer>
<ID1>30</ID1>
<ID2>58878</ID2>
<OtherElements />
</Customer>
</Customers>
</Root>

the output is

<Root>
  <Customers>
    <Customer>
      <ID1>30</ID1>
      <ID2>58878</ID2>
      <OtherElements />
    </Customer>
    <Customer>
      <ID1>100</ID1>
      <ID2>5555</ID2>
      <OtherElements />
    </Customer>
    <Customer>
      <ID1>200</ID1>
      <ID2>445</ID2>
      <OtherElements />
    </Customer>
  </Customers>
</Root>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.