开发者

How to swap two XML elements in linq to xml

I want to swap two xml elements. How do i do this? Here is the 开发者_运维技巧code. I tried the solution here but it did not work for me after all. I want to swap the both elements. When I run the program the elements are not swapped but when I call ToList() it is swapped in the List but not swapped in the doc variable

<template id="12">
  <tabs>
    <tab>
      <name>test1</name>
      <description />
    </tab>
    <tab>
      <name>test2</name>
      <description />
    </tab>
  </tabs>
</template>

Here is the code to swap them

        var doc = XDocument.Parse(q.XMLtext);
        var Current = doc.ElementOrDefault("template").ElementOrDefault("tabs").ElementsOrDefault("tab").Where(x => (string)x.Element("name") == name).FirstOrDefault();
        var Previous = Current.PreviousNode as XElement;
        var Next = Current.NextNode as XElement;
        var CurrentName = (string)Current.ElementOrDefault("name");
        var PreviousName = (string)Previous.ElementOrDefault("name");
        var NextName = (string)Next.ElementOrDefault("name");
        if (MoveDirection == (int)MoveType.Up)
        {
            doc.ElementOrDefault("template").ElementOrDefault("tabs").ElementsOrDefault("tab").Where(x => (string)x.Element("name") == CurrentName || (string)x.Element("name") == PreviousName).Reverse();

        }
        else
            //doc.ElementOrDefault("template").ElementOrDefault("tabs").ElementsOrDefault("tab").Where(x => x == Current || x == Next).Take(2).Reverse();

        q.XMLtext = doc.ToString();
        context.SaveChanges();


I'm afraid I haven't quite worked out exactly which elements you want to swap, but XElement.ReplaceWith is what you're after, I believe. Here's a short but complete program which demonstrates it:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xml = @"
<root>
  <element1/>
  <element2/>
  <element3/>
  <element4/>
  <element5/>
</root>";
        XDocument doc = XDocument.Parse(xml);
        XElement x = doc.Root.Element("element2");
        XElement y = doc.Root.Element("element4");
        x.ReplaceWith(y);
        y.ReplaceWith(x);
        Console.WriteLine(doc);
    }
}

This swaps element2 and element4.

Note that this works because the first x.ReplaceWith(y) actually creates a copy of y, leaving the original in its existing location... ready to be replaced with x.


.Reverse() returns the elements in reverse order. It's doesn't swap them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜