插入XElement以使用LinqToXml包围另一个XElement

Joh*_*ino 1 c# linq-to-xml

假设我有以下xml,

<Where><BeginsWith>...</BeginsWith></Where>
Run Code Online (Sandbox Code Playgroud)

现在我想"插入"一个<And>围绕BeginsWith子句的子句,所以它看起来像这样,

<Where><And><BeginsWith>...</BeginsWith></And></Where>
Run Code Online (Sandbox Code Playgroud)

如何使用LinqToXml实现这一目标?

我基本上做的Add方法 where.Add(new XElement("And"))只会在BeginsWith之后添加"And",就像这样,

<Where><BeginsWith>...</BeginsWith><And /></Where>
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

  • 获取BeginsWith元素
  • XNode.Remove()它将其从Where中删除
  • 添加And元素
  • 将BeginsWith添加到And元素(或使用它作为内容开始创建And元素)

例如:

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);
    }        
}
Run Code Online (Sandbox Code Playgroud)