Justin Homes
Justin Homes

Reputation: 3799

Sort XmlElement by Attribute value

I have

XmlElement root;

that contains structure like this

<?xml version="1.0" encoding="us-ascii"?>
<EntityCollection xmlns="">
    <Application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <id>C</id>
        <CDate>2010-06-29T00:00:00</CDate>
        <Applicants>
            <PersonID>1</PersonID>     
            <Age>4651</Age>
            <IncomeCollection>
                <Amount>20</Amount>
                <Frequency>W</Frequency>
            </IncomeCollection>
        </Applicants>
        <Applicants>
            <PersonID>15</PersonID>     
            <Age>4651</Age>
            <IncomeCollection>
                <Amount>20</Amount>
                <Frequency>W</Frequency>
            </IncomeCollection>
        </Applicants>
        <Applicants>
            <PersonID>6</PersonID>     
            <Age>4651</Age>
            <IncomeCollection>
                <Amount>20</Amount>
                <Frequency>W</Frequency>
            </IncomeCollection>
        </Applicants>
        <tag>N</tag>
    </Application>
</EntityCollection>

i want to sort the applicants by PersonID so that the result be like below:

<?xml version="1.0" encoding="us-ascii"?>
<EntityCollection xmlns="">
    <Application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <id>C</id>
        <CDate>2010-06-29T00:00:00</CDate>
        <Applicants>
            <PersonID>1</PersonID>     
            <Age>4651</Age>
            <IncomeCollection>
                <Amount>20</Amount>
                <Frequency>W</Frequency>
            </IncomeCollection>
        </Applicants>
        <Applicants>
            <PersonID>6</PersonID>     
            <Age>4651</Age>
            <IncomeCollection>
                <Amount>20</Amount>
                <Frequency>W</Frequency>
            </IncomeCollection>
        </Applicants>
        <Applicants>
            <PersonID>15</PersonID>     
            <Age>4651</Age>
            <IncomeCollection>
                <Amount>20</Amount>
                <Frequency>W</Frequency>
            </IncomeCollection>
        </Applicants>
        <tag>N</tag>
    </Application>
</EntityCollection>

Upvotes: 0

Views: 726

Answers (1)

I4V
I4V

Reputation: 35353

Altought XmlParsers don't guarantee that you will get the elements in the order in xml file, here is a solution using Linq2Xml

var xDoc = XDocument.Load(fname);
var applicants = xDoc.Descendants("Applicants")
                     .OrderBy(a=>(int)a.Element("PersonID"))
                     .ToList();
applicants.ForEach(a=>a.Remove());
xDoc.Root.Element("Application").Add(applicants);
xDoc.Save(fname);

Upvotes: 1

Related Questions