我有一些XML如何按属性对XDocument进行排序?
<Users>
<User Name="Z"/>
<User Name="D"/>
<User Name="A"/>
</User>
我想名称到那种。我使用XDocument
加载该xml。我如何查看按名称排序的xml?
我有一些XML如何按属性对XDocument进行排序?
<Users>
<User Name="Z"/>
<User Name="D"/>
<User Name="A"/>
</User>
我想名称到那种。我使用XDocument
加载该xml。我如何查看按名称排序的xml?
您可以按使用LINQ to XML,如果XmlDocument的是不是我做的情况下
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));
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));
名称是属性,而不是元素;) – 2010-02-09 22:14:50
@Daniel:哦,废话!哦,我的坏。 OP可以纠正 – kd7 2010-02-09 22:24:19
,但我有一个例外。 “至少有一个对象必须实现IComparable”。 – cagin 2010-02-09 20:37:18
它需要是'node.Attribute(“Name”)。值' – 2010-02-09 21:32:01
仅供参考,做一个stright'node.Attribute(“Name”).Value'会留下一个空引用异常,如果该属性缺失的话。此外,如果XML文档指定了一个模式,只是执行'node.Attribute(“Name”)'也不够用,因为您必须使用适当的'XName'来查找属性。 – 2010-02-09 22:14:22