2010-02-09 40 views

回答

13

您可以按使用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)); 
+0

,但我有一個例外。 「至少有一個對象必須實現IComparable」。 – cagin 2010-02-09 20:37:18

+0

它需要是'node.Attribute(「Name」)。值' – 2010-02-09 21:32:01

+0

僅供參考,做一個stright'node.Attribute(「Name」).Value'會留下一個空引用異常,如果該屬性缺失的話。此外,如果XML文檔指定了一個模式,只是執行'node.Attribute(「Name」)'也不夠用,因爲您必須使用適當的'XName'來查找屬性。 – 2010-02-09 22:14:22

0
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)); 
+0

名稱是屬性,而不是元素;) – 2010-02-09 22:14:50

+0

@Daniel:哦,廢話!哦,我的壞。 OP可以糾正 – kd7 2010-02-09 22:24:19

相關問題