这是我给出的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");
但是,我在行中出现错误&#34; Validations.AppendChild(validation)&#34; as 对象引用未设置为对象的实例。请提出一些解决方法。
答案 0 :(得分:3)
你可以这样做
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");
答案 1 :(得分:0)
您的SelectSingleNode()
没有匹配任何元素,因此是空引用异常。除了冲突的双引号问题,您应该使用@attribute_name
模式使用XPath引用属性。所以正确的表达方式是:
originalXml.SelectSingleNode("/Processes/Process[@Name='Process1']/Validations");