c# - 如何在 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);
这不起作用,它运行但没有任何反应。我不认为循环是最好的方法,我想知道是否有更好的方法。我环顾四周,但似乎找不到我要找的东西。
解决方案
在这里,我建议使用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
推荐阅读
- node.js - 收到错误“数字信封例程”,原因:“不支持”,代码:“ERR_OSSL_EVP_UNSUPPORTED”
- r - 将参数传递给使用 dplyr R 的函数内的回归模型
- amazon-web-services - 如何在现有的 dynamodb 表上创建 2017.11.29 版本的全局表和数据?
- java - KafkaConsumer visibility across threads
- amazon-web-services - CloudWatch 警报 - 异常检测
- php - 使用 laravel 8 仅验证部分工作
- pyspark - 在事件 SqlSensor 上运行作业(插入表中)
- c# - 在 C# 中对字典列表进行分组
- java - 如何将我的Optaplanner程序封装成一个函数供其他平台调用?
- vim - 格式化vim中的文本列(对齐)