多元素排序XmlDocument [没有LINQ]

时间:2013-11-27 15:44:20

标签: xml xpath c#-3.0 xmldocument

我有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,请帮助我实现这一目标。

由于

1 个答案:

答案 0 :(得分:3)

.NET框架的XPath / XSLT实现在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>