CSharp - LINQ XML InDocumentOrder

Introduction

The InDocumentOrder operator can be called on a sequence of nodes.

It returns a sequence containing each source node sorted in document order.

Prototypes

public static IEnumerable<T> InDocumentOrder<T> (
        this IEnumerable<T> source
      ) where T : XNode

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program//from   w w w  . j a  va 2s . c o m
{
    static void Main(string[] args){
            XDocument xDocument = new XDocument(
              new XElement("Books",
                new XElement("Book",
                  new XAttribute("type", "Author"),
                  new XComment("This is a new author."),
                  new XElement("FirstName", "Joe"),
                  new XElement("LastName", "Ruby")),
                new XElement("Book",
                  new XAttribute("type", "Editor"),
                  new XElement("FirstName", "PHP"),
                  new XElement("LastName", "Python"))));
            
            IEnumerable<XNode> nodes =
              xDocument.Element("Books").Elements("Book").
                Nodes().Reverse();
            
            //  First, we will display the source nodes.
            foreach (XNode node in nodes)
            {
              Console.WriteLine("Source node: {0}", node);
            }
            
            //  Now, we will display each source node's child nodes.
            foreach (XNode node in nodes.InDocumentOrder())
            {
              Console.WriteLine("Ordered node: {0}", node);
            }
    }
}

Result