2014-11-24 69 views
0

我有下面的menioned XML。如何排序嵌套节点xml

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

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

+1

什么是期望的输出? XML或类型集合等? – 2014-11-24 10:39:20

回答

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>"; 
}