XMLdocument Sort

后端 未结 1 955
陌清茗
陌清茗 2021-01-14 23:46

I\'ve figured out how to append nodes to my rss document in the right structyre. I now need to sort it in the pubDate order and then output to screen. Looking at the example

1条回答
  •  半阙折子戏
    2021-01-15 00:01

    You can do this fairly quickly and painlessly using Linq to XML.

    If you parse your XML using XElement.Parse(...) you can then use OrderBy or OrderByDescending functions and alter the content pretty easily. Here is a simplified example:

    XElement element = XElement.Parse(@"
    
    
    
    
    
    
    
    ");
    
    var elements = element.Element("channel")
                    .Elements("item")
                    .OrderBy(e => DateTime.ParseExact(e.Attribute("pubDate").Value, "dd/MM/yyyy", null))
                    .Select(e => new XElement("item",
                        new XElement("title", e.Attribute("title").Value),
                        new XElement("pubDate", e.Attribute("pubDate").Value))); // Do transform here.
    
                element.Element("channel").ReplaceAll(elements);
    
                Console.Write(element.ToString());
    

    The XML is not going to be the same as yours, but hopefully it gives you an idea of what you could do. You can just specify XElement and XAttribute objects as content for your new XML, this outputs the following:

    
      
        
          something3
          10/02/2010
        
        
          something4
          22/01/2011
        
        
          something2
          24/03/2012
        
        
          something
          22/11/2012
        
      
    
    

    I hope this is useful.

    0 讨论(0)
提交回复
热议问题