我有一些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