这是我给定的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");