我有下面的Xml结构。
<Root>
<Customers>
<Customer>
<ID1>100</ID1>
<ID2>5555</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>200</ID1>
<ID2>445</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>30</ID1>
<ID2>58878</ID2>
<OtherElements />
</Customer>
<Customers>
</Root>
我想用ID1 ASC和ID2 ASC排序顺序重新安排客户节点。请帮助我在没有XSLT和LINQ的情况下实现这一点。
感谢
好吧,.NET框架的XPath/XLTL实现在XPathExpression
:上公开了一个排序功能
XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
XPathExpression customers = XPathExpression.Compile("/Root/Customers/Customer");
customers.AddSort("ID1", XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, "", XmlDataType.Number);
customers.AddSort("ID2", XmlSortOrder.Ascending, XmlCaseOrder.LowerFirst, "", XmlDataType.Number);
XmlElement parent = doc.DocumentElement["Customers"];
foreach (XPathNavigator cust in doc.CreateNavigator().Select(customers))
{
parent.AppendChild(cust.UnderlyingObject as XmlNode);
}
doc.Save(Console.Out); // for testing, use Save("file.xml") to save
输入为
<?xml version="1.0" encoding="utf-8" ?>
<Root>
<Customers>
<Customer>
<ID1>100</ID1>
<ID2>5555</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>200</ID1>
<ID2>445</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>30</ID1>
<ID2>58878</ID2>
<OtherElements />
</Customer>
</Customers>
</Root>
输出是
<Root>
<Customers>
<Customer>
<ID1>30</ID1>
<ID2>58878</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>100</ID1>
<ID2>5555</ID2>
<OtherElements />
</Customer>
<Customer>
<ID1>200</ID1>
<ID2>445</ID2>
<OtherElements />
</Customer>
</Customers>
</Root>