如何解决如何在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>
节点上添加一个新节点。新的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);
这不起作用,它运行但什么也没发生。我认为循环不是最好的方法,我想知道是否有更好的方法。我环顾四周,但似乎找不到我想要的东西。
解决方法
在这里,我建议使用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
,
最有可能的解决方案是更多。可行:
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。