2010-02-09 37 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

相关问题