我有一些XML
<Users>
<User Name="Z"/>
<User Name="D"/>
<User Name="A"/>
</User>
我想按Name对其进行排序。我使用XDocument
加载该xml。如何查看按名称排序的xml?
我有一些XML
<Users>
<User Name="Z"/>
<User Name="D"/>
<User Name="A"/>
</User>
我想按Name对其进行排序。我使用XDocument
加载该xml。如何查看按名称排序的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));
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));
node.Attribute("Name").Value
。 - Daniel Schaffernode.Attribute("Name").Value
会导致空引用异常。此外,如果 XML 文档指定了模式,仅使用node.Attribute("Name")
也不够,因为您必须使用适当的XName
查找该属性。 - Daniel Schaffer