Sorting all the elements in a XDocument

前端 未结 4 620
孤城傲影
孤城傲影 2020-12-10 02:56

I have a XDocument where I\'d like to sort all of the elements alphabetically. Here\'s a simplified version of the structure:


 
         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 03:21

    I think these extension method work best.

    public static class XmlLinq
    {
      public static void Sort(this XElement source, bool sortAttributes = true)
      {
         if (source == null)
            throw new ArgumentNullException("source");
    
         if (sortAttributes)
            source.SortAttributes();
    
         List sortedChildren = source.Elements().OrderBy(e => e.Name.ToString()).ToList();
         source.RemoveNodes();
    
         sortedChildren.ForEach(c => source.Add(c));
         sortedChildren.ForEach(c => c.Sort());
      }
    
      public static void SortAttributes(this XElement source)
      {
         if (source == null)
            throw new ArgumentNullException("source");
    
         List sortedAttributes = source.Attributes().OrderBy(a => a.ToString()).ToList();
         sortedAttributes.ForEach(a => a.Remove());
         sortedAttributes.ForEach(a => source.Add(a));
      }
    }
    

提交回复
热议问题