siddharth kumar singh siddharth kumar singh - 1 year ago 82
C# Question

Adding child node for a node inside XML using C#

Here is my given XML:-

<?xml version="1.0" encoding="utf-8"?>
<Process Name="Process1" Namespace="" Methodname="">

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

XmlDocument originalXml = new XmlDocument();
XmlNode Validations = originalXml.SelectSingleNode("/Processes/Process[Name="Process1"]/Validations");
XmlNode Validation = originalXml.CreateNode(XmlNodeType.Element, "Validation",null);
Validation.InnerText = "This is my new Node";

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.

Answer Source

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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download