代码之家  ›  专栏  ›  技术社区  ›  Johan Leino

插入Xelement以用LinqToXML包围另一个Xelement

  •  1
  • Johan Leino  · 技术社区  · 16 年前

    假设我有以下XML,

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

    现在我想“插入”一个 <And> 围绕beginsWith子句的子句,因此后面看起来像这样,

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

    我如何用linqtoxml完成这个任务?

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

    <Where><BeginsWith>...</BeginsWith><And /></Where>
    
    2 回复  |  直到 16 年前
        1
  •  6
  •   Jon Skeet    16 年前
    • 获取beginswith元素
    • 呼叫 XNode.Remove() 把它从哪里移走
    • 添加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);
        }        
    }
    
        2
  •  1
  •   jrista    16 年前

    我不知道有什么原子操作能为你做到这一点。您可能需要添加“and”元素,然后在其中移动beginswith元素。

    推荐文章