gpt4 book ai didi

c# - 使用 C# 在 XML 节点内添加子节点

转载 作者:行者123 更新时间:2023-11-30 21:46:51 26 4
gpt4 key购买 nike

这是我给定的 XML:-

<?xml version="1.0" encoding="utf-8"?>
<Processes>
<Process Name="Process1" Namespace="" Methodname="">
<Validations/>
<Transformations/>
<Routings/>
</Process>
</Processes>

我想在 Validations 中添加新节点 Validation 并且为此我编写了以下代码:-

XmlDocument originalXml = new XmlDocument();
originalXml.Load(@"C:\Users\Sid\Desktop\Process\Process1.xml");
XmlNode Validations = originalXml.SelectSingleNode("/Processes/Process[Name="Process1"]/Validations");
XmlNode Validation = originalXml.CreateNode(XmlNodeType.Element, "Validation",null);
Validation.InnerText = "This is my new Node";
Validations.AppendChild(Validation);
originalXml.Save(@"C:\Users\Sid\Desktop\Process\Process1.xml");

但是,我在“Validations.AppendChild(validation)”行中遇到错误,因为未将对象引用设置为对象的实例。请提出一些修复方法。

最佳答案

你可以这样做

XDocument doc = XDocument.Load(@"C:\Users\Sid\Desktop\Process\Process1.xml");
var a = doc.Descendants("Validations").FirstOrDefault();
a.Add(new XElement("Validation", "This is my new Node"));
doc.Save(@"C:\Users\Sid\Desktop\Process\Process1.xml");

关于c# - 使用 C# 在 XML 节点内添加子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com