Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在XML中仅在父节点之后添加新节点_C#_.net_Xml_Linq - Fatal编程技术网

C# 如何在XML中仅在父节点之后添加新节点

C# 如何在XML中仅在父节点之后添加新节点,c#,.net,xml,linq,C#,.net,Xml,Linq,我使用C#xml和Linq将三个xml文档合并为一个。在将其保存为“Final.xml”之前,我想在父节点下添加一个节点,并在关闭父节点之前的底部添加一个节点 我的XML结构如下所示: <Main> <Action> <URL /> </Action> <Execute> <URL /> <MetaData /> </Execute>

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

我的XML结构如下所示:

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

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

很可能有更奇特的解决方案,但是。这项工作:

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);
var xmlstring=“123”;
var doc=XDocument.Parse(xmlstring);
var childs=doc.Root.Elements().ToList();
doc.Root.RemoveAll();
var parent=新的XElement(“父项”);
添加(childs);
单据根目录新增(上级);

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

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

因此,通过使用
XDocument
,解决方案有多简单:

var doc=XDocument.Parse(@)
");
var mainCopy=new-XElement(doc.Root.Name);//创建“主”节点的空副本
doc.Root.Name=“新建”//将“主”替换为“新”
doc=新的XDocument(新的XElement(mainCopy.Name,doc.Root));//创建包装器XML

Monica,你认为你的问题得到了回答吗?如果没有,请指导我们如何帮助您。但如果你认为你的问题有答案,请将其标记为接受。
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);