首页 > 解决方案 > 如何在 XML 中的父节点之后添加新节点

问题描述

我正在使用 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>节点。新的结构需要如下所示:

<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);

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

标签: c#.netxmllinq

解决方案


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

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

因此,通过使用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

推荐阅读