문제

I have below Xml structure.

<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>

I would like to re-arrange Customer Nodes with ID1 ASC, AND ID2 ASC sorting Order. Please help me to achieve this without XSLT and LINQ.

Thanks

도움이 되었습니까?

해결책

Well the .NET framework's XPath/XSLT implementation exposes a sort feature on 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

With the input being

<?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>

the output is

<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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top