Click here to Skip to main content
15,917,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a C# Novice and have a problem which I hope someone can help me with?

I have a very small code snippet to Sort a large XML file.
C#
using System;
using System.Linq;
using System.Xml.Linq;

public class XMLsort
{
  public static void Sort(string netMyFile, string netOutFile)
  {
    XElement root = XElement.Load(netMyFile);
    var orderedtabs = root.Elements("aidocument")
        .OrderBy(xtab => (string)xtab.Element("aidocumentheader").Element("accountno"))
        .ToArray();
    root.RemoveAll();
    foreach (XElement tab in orderedtabs)
        root.Add(tab);
    root.Save(netOutFile);
  }
}

This works very well however it is removing some root tags and I would like to know how to retain them in the sorted output?

Original XML is:
XML
<?xml version="1.0" encoding="windows-1252" ?>
<aitransmission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation="C:\Myschema\mysampleschema.xml">
<transmissionid>20120730DOCS</transmissionid>
<transmissiontime>23:02:19</transmissiontime>
<transmissiondate>2012-27-07</transmissiondate>
<transmissionsource>fromprd</transmissionsource>
<transmissioncount>71</transmissioncount>
    <aidocument documenttype="adv">
     [data]
    </aidocument>
    <aidocument documenttype="adv">
     [data]
    </aidocument>
    <aidocument documenttype="adv">
     [data]
    </aidocument>
</aitransmission>


Returned XML is:
XML
<?xml version="1.0" encoding="utf-8"?>
<aitransmission>
    <aidocument documenttype="adv">
     [sorted data]
    </aidocument>
    <aidocument documenttype="adv">
     [sorted data]
    </aidocument>
    <aidocument documenttype="adv">
     [sorted data]
    </aidocument>

So the 'transmission*' tags are being stripped.

Can anybody suggest how I can amend my code to deal with this scenario please?

Thanks

Andy

code blocks corrected
Posted
Updated 1-Oct-14 1:20am
v3
Comments
Sinisa Hajnal 1-Oct-14 7:03am    
Don't call remove all, remove just what is sorting?

1 solution

Try something like this:
C#
public static void Sort(string netMyFile, string netOutFile)
{
    var document = XDocument.Load(netMyFile);

    var orderedTabs = document.Root.Elements("aidocument")
        .OrderBy(xtab => (string)xtab.Element("aidocumentheader").Element("accountno"))
        .ToList();

    orderedTabs.ForEach(xtab => xtab.Remove());
    document.Root.Add(orderedTabs);
    document.Save(netOutFile);
}
 
Share this answer
 
Comments
andrew payne 1-Oct-14 9:59am    
Hi Richard

Thanks so much - that works like a charm! And it seems to run far more efficiently too!

Thanks again

Andy

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900