这个发生挺有意思的,有时候我们打乱文档元素原有的顺序,比方说对元素顺序进行倒转Reverse
但是有时候又需要取回原有的顺序,这个时候就可以使用InDocumentOrder,下面是例子
XDocument xDocument = new XDocument( new XElement("BookParticipants", new XElement("BookParticipant", new XAttribute("type", "Author"), new XComment("This is a new author."), new XElement("FirstName", "Joe"), new XElement("LastName", "Rattz")), new XElement("BookParticipant", new XAttribute("type", "Editor"), new XElement("FirstName", "Ewan"), new XElement("LastName", "Buckingham")))); IEnumerable<XNode> nodes = xDocument.Element("BookParticipants").Elements("BookParticipant"). 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); }
这里面已经对结点顺序进行了倒转
IEnumerable<XNode> nodes =
xDocument.Element("BookParticipants").Elements("BookParticipant").
Nodes().Reverse();
下面的输出可以看到InDocumentOrder所起的作用
Source node: <LastName>Buckingham</LastName>
Source node: <FirstName>Ewan</FirstName>
Source node: <LastName>Rattz</LastName>
Source node: <FirstName>Joe</FirstName>
Source node: <!--This is a new author.-->
Ordered node: <!--This is a new author.-->
Ordered node: <FirstName>Joe</FirstName>
Ordered node: <LastName>Rattz</LastName>
Ordered node: <FirstName>Ewan</FirstName>
Ordered node: <LastName>Buckingham</LastName>