tags:

views:

267

answers:

2

Let´s say I have the following xml,

<Where><BeginsWith>...</BeginsWith></Where>

and now I want to "insert" an <And> clause that surrounds the BeginsWith clause so it looks like this afterward,

<Where><And><BeginsWith>...</BeginsWith></And></Where>

How do I accomplish that with LinqToXml?

The Add method where I essentially do where.Add(new XElement("And")) will only add the the "And" after BeginsWith, like this,

<Where><BeginsWith>...</BeginsWith><And /></Where>
+1  A: 

I don't know that there is any atomic operation that will do this for you. You will likely have to add the "And" element, then move the BeginsWith element inside it.

jrista
+4  A: 
  • Get the BeginsWith element
  • Call XNode.Remove() on it to remove it from Where
  • Add the And element
  • Add BeginsWith to the And element (or create the And element using it as the content to start with)

For example:

using System;
using System.Xml.Linq;

public class Test
{
    public static void Main()
    {
        XElement where = XElement.Parse
            ("<Where><BeginsWith>...</BeginsWith></Where>");
        XElement beginsWith = where.Element("BeginsWith");
        beginsWith.Remove();
        where.Add(new XElement("And", beginsWith));
        Console.WriteLine(where);
    }        
}
Jon Skeet
Thanks Jon, that works like a charm :-)
Johan Leino