【发布时间】:2011-01-14 23:34:22
【问题描述】:
我有一些 XML
<Users>
<User Name="Z"/>
<User Name="D"/>
<User Name="A"/>
</User>
我想按 Name 对其进行排序。我使用XDocument 加载该xml。如何查看按名称排序的 xml?
【问题讨论】:
标签: c# sorting linq-to-xml
我有一些 XML
<Users>
<User Name="Z"/>
<User Name="D"/>
<User Name="A"/>
</User>
我想按 Name 对其进行排序。我使用XDocument 加载该xml。如何查看按名称排序的 xml?
【问题讨论】:
标签: c# sorting linq-to-xml
如果 XmlDocument 不是这种情况,您可以使用 LINQ to Xml 进行排序
XDocument input = XDocument.Load(@"input.xml");
XDocument output = new XDocument(
new XElement("Users",
from node in input.Root.Elements()
orderby node.Attribute("Name").Value descending
select node));
【讨论】:
node.Attribute("Name").Value
node.Attribute("Name").Value 会使您打开空引用异常。此外,如果 XML 文档指定了一个模式,那么仅仅使用 node.Attribute("Name") 也是不够的,因为您必须使用正确的 XName 来查找属性。
XDocument xdoc = new XDocument(
new XElement("Users",
new XElement("Name", "Z"),
new XElement("Name", "D"),
new XElement("Name", "A")));
var doc = xdoc.Element("Users").Elements("Name").OrderBy(n => n.Value);
XDocument doc2 = new XDocument(new XElement("Users", doc));
【讨论】: