简体   繁体   中英

Xml.Linq: Reversing child-nodes of a XML

I have the following XML file created in runtime as per user input.

<Parent>
    <X1>1</X1>
    <X2>
        <Y1>
            <Rank>4</Rank>
        </Y1>
        <Y1>
            <Rank>3</Rank>
        </Y1>
        <Y1>
            <Rank>2</Rank>
        </Y1>
        <Y1>
            <Rank>1</Rank>
        </Y1>
    </X2>
</Parent>

Now, I want to reverse the child node such a way <Rank> arranged in ascending order. I want the following output

<Parent>
    <X1>1</X1>
    <X2>
        <Y1>
            <Rank>1</Rank>
        </Y1>
        <Y1>
            <Rank>2</Rank>
        </Y1>
        <Y1>
            <Rank>3</Rank>
        </Y1>
        <Y1>
            <Rank>4</Rank>
        </Y1>       
    </X2>
</Parent>

This problem is created because I am using the AddFirst method. I didn't find any method which is exact opposite of AddFirst.

You can use Reverse

Example:

static void Main(string[] args)
{
    XElement srcTree = new XElement("Parent",
                new XElement("X1", 1),
                new XElement("X2",
                    new XElement("Y1", new XElement("Rank", 4)),
                    new XElement("Y1", new XElement("Rank", 3)),
                    new XElement("Y1", new XElement("Rank", 2)),
                    new XElement("Y1", new XElement("Rank", 1)))
            );

    var reverseList = srcTree.Elements("X2").Descendants("Y1").InDocumentOrder().Reverse().ToList();

    srcTree.Element("X2").Remove();
    srcTree.Add(new XElement("X2", reverseList));


    Console.WriteLine(srcTree);
    Console.ReadLine();
}

It will give you desired result:

<Parent>
  <X1>1</X1>
  <X2>
    <Y1>
      <Rank>1</Rank>
    </Y1>
    <Y1>
      <Rank>2</Rank>
    </Y1>
    <Y1>
      <Rank>3</Rank>
    </Y1>
    <Y1>
      <Rank>4</Rank>
    </Y1>
  </X2>
</Parent>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM