2

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.

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

great happy coding
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.