Reputation: 57
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.
Upvotes: 2
Views: 5254
Reputation: 89325
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");
Upvotes: 0
Reputation: 7352
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");
Upvotes: 3