简体   繁体   中英

Adding child node inside a XML node using C#

Here is my given XML:-

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

I want to add new node Validation inside Validations and for that i have written the following code:-

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");

But, I am getting error in the line "Validations.AppendChild(validation)" as Object reference not set to an instance of an object . Please suggest some way to fix it.

You can do by this

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");

Your SelectSingleNode() didn't match any element, hence the null-reference exception. Beside the conflicting double-quotes problem, you should use @attribute_name pattern to reference attribute using XPath. So the correct expression would be :

originalXml.SelectSingleNode("/Processes/Process[@Name='Process1']/Validations");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM