XMLdocument Sort

后端 未结 1 935
陌清茗
陌清茗 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(@"
    <rss>
    <channel>
    <item title='something' pubDate='22/11/2012'/>
    <item title='something2' pubDate='24/03/2012'/>
    <item title='something3' pubDate='10/02/2010'/>
    <item title='something4' pubDate='22/01/2011'/>
    </channel>
    </rss>");
    
    var elements = element.Element("channel")
                    .Elements("item")
                    .OrderBy<XElement, DateTime>(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:

    <rss>
      <channel>
        <item>
          <title>something3</title>
          <pubDate>10/02/2010</pubDate>
        </item>
        <item>
          <title>something4</title>
          <pubDate>22/01/2011</pubDate>
        </item>
        <item>
          <title>something2</title>
          <pubDate>24/03/2012</pubDate>
        </item>
        <item>
          <title>something</title>
          <pubDate>22/11/2012</pubDate>
        </item>
      </channel>
    </rss>
    

    I hope this is useful.

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