LINQ To XML:按文档定义的元素顺序显示元素InDocumentOrder

本文介绍了一种在XML文档中恢复节点原始顺序的方法。通过使用InDocumentOrder方法,即使在节点顺序被打乱的情况下,也能确保输出按照原始顺序排列。示例展示了如何在节点顺序被反转后重新获得正确的顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个发生挺有意思的,有时候我们打乱文档元素原有的顺序,比方说对元素顺序进行倒转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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值