如何对嵌套节点xml进行排序

时间:2014-11-24 10:29:12

标签: c# xml

我有以下的xion。

    <?xml version="1.0" encoding="UTF-8"?>
<insiders>
   <insider>
      <linkages>
         <linkage>
            <owner id="112025">
               <namestrings>
                  <namestring />
               </namestrings>
            </owner>
            <relationshipHistory>
               <relationship code="201" />
            </relationshipHistory>
         </linkage>
      </linkages>
   </insider>
   <insider>
      <linkages>
         <linkage>
            <owner id="100354">
               <namestrings>
                  <namestring>KAITUE RAIMO KUOLINPESÄ</namestring>
               </namestrings>
            </owner>
            <relationshipHistory>
               <relationship code="302">
                  <from>1998-10-23</from>
               </relationship>
            </relationshipHistory>
         </linkage>
         <linkage>
            <owner id="126799">
               <namestrings>
                  <namestring />
               </namestrings>
            </owner>
            <relationshipHistory>
               <relationship code="204">
                  <from>2014-09-09</from>
               </relationship>
               <relationship code="201">
                  <to>2014-09-08</to>
               </relationship>
            </relationshipHistory>
         </linkage>
      </linkages>
   </insider>
</insiders>

我想根据relationshipHistory属性对code节点进行排序,在提到的xml code=201元素之后应首先code=204。{ 任何人都可以帮助我,我该怎么办?

1 个答案:

答案 0 :(得分:1)

我就是这样做的:

我假设你可以选择'relationshipHistory'元素,所以我只显示排序。

class Program
{
    static void Main(string[] args)
    {
        XDocument xdoc = XDocument.Parse(xml);
        XElement history = xdoc.Element("relationshipHistory");
        IEnumerable<XElement> histories = history.Elements();
        // Sort elements and create new elements because the RemoveAll method will delete the old ones.
        IEnumerable<XElement> historiesSorted = 
            histories
            .OrderBy(x => int.Parse(x.Attribute("code").Value))
            .Select(x => new XElement(x))
            .ToList();
        // Remove the old elements.
        history.RemoveAll();
        // Add the sorted elements to the parent element.
        foreach (var item in historiesSorted)
        {
            history.Add(item);
        }
    }

    static string xml = @"<?xml version='1.0' encoding='UTF-8\'?>
        <relationshipHistory>
            <relationship code='204'>
                <from>2014-09-09</from>
            </relationship>
            <relationship code='201'>
                <to>2014-09-08</to>
            </relationship>
        </relationshipHistory>";
}