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

1 回答 1

1

Altought XmlParsers 不保证您将在 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);
于 2013-06-06T13:45:28.253 回答