按属性值排序XmlElement

时间:2013-06-06 13:37:28

标签: c# .net xml c#-4.0

我有

XmlElement root;

包含这样的结构

<?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>

我想按PersonID对申请人进行排序,以便结果如下:

<?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>

1 个答案:

答案 0 :(得分:1)

虽然Xml Parsers不保证你会在xml文件中获得顺序中的元素,但这是一个使用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);