如何在XML中的父节点之后添加新节点

时间:2020-08-27 10:42:36

标签: c# .net xml linq

我正在使用C#XML和Linq将三个xml文档合并为一个。在将其另存为“ Final.xml”之前,我想在父节点下方和关闭父节点之前的底部添加一个<New>节点。

我有这样的XML结构:

<Main>
   <Action>
      <URL />
   </Action>
   <Execute>
      <URL />
      <MetaData />
   </Execute>
   <Action>
      <URL />
   </Action>
   <Assert>
      <URL />
   </Assert>
</Main>

我想在<Main>节点下和</Main>节点上添加一个新节点。新的Scructure需要如下所示:

<Main>
  <New>
    <Action>
      <URL />
   </Action>
   <Execute>
      <URL />
      <MetaData />
   </Execute>
   <Action>
      <URL />
   </Action>
   <Assert>
      <URL />
   </Assert>
  </New>
</Main>

我尝试过以下代码:

...
var xelem3 = xdoc4.Root.Elements();
xdoc1.Root.LastNode.AddAfterSelf(xelem3);

var Tests = xdoc1.Root.Elements("Test");


foreach (var test in Tests)
  {
    test.AddBeforeSelf(new XElement("New"));
  }

   xdoc1.Save(FinalDoc);

这不起作用,它运行但什么也没发生。我认为循环不是最好的方法,我想知道是否有更好的方法。我环顾四周,但似乎找不到我想要的东西。

2 个答案:

答案 0 :(得分:1)

在这里,我建议使用XDocument(LINQ to XML)而不是XmlDocument(与.NET 3.0或更低版本一起使用),因为它更新且非常简单。

有关更多信息,请查看this官方文档。

因此,通过使用XDocument,以下是解决方案的简单程度:

var doc = XDocument.Parse(@"<Main>
    <Action>
        <URL />
    </Action>
    <Execute>
        <URL />
        <MetaData />
    </Execute>
    <Action>
        <URL />
    </Action>
    <Assert>
        <URL />
    </Assert>
</Main>");

var mainCopy = new XElement(doc.Root.Name); // creating an empty copy of the "Main" node
doc.Root.Name = "New"; // replace the "Main" with "New"

doc = new XDocument(new XElement(mainCopy.Name, doc.Root)); // creating a wrapper XML

答案 1 :(得分:0)

最有可能的解决方案是更多。可行:

var xmlstring = "<Root><Child1>1</Child1><Child2>2</Child2><Child3>3</Child3></Root>";
var doc = XDocument.Parse(xmlstring);

var childs = doc.Root.Elements().ToList();
doc.Root.RemoveAll();

var parent = new XElement("Parent");
parent.Add(childs);

doc.Root.Add(parent);