Need to open an XML file and add a node?

It is actually very simple

Here’s how:

Sample XML file:

<?xml version="1.0"?>
<HelpData
    xmlns:xsi=
    "http://www.w3.org
/2001/XMLSchema-instance"
    xmlns:xsd=

http://www.w3.org

/2001/XMLSchema>
   <helpButtonUrls>
       <HelpButtonUrl>
         <buttonName>
	BugReport</buttonName>
         <url>C:BugRep.exe</url>
       </HelpButtonUrl>
   <HelpButtonUrl>
</HelpData>

We want to add another HelpButtonNode:
private void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
//create new instance of XmlDocument
XmlDocument doc = new XmlDocument();
//load from file
doc.Load(XmlFilePath);
//create main node
XmlNode node = doc.CreateNode(XmlNodeType.Element, “HelpButtonUrl”, null);
//create the nodes first child
XmlNode ButtonName = doc.CreateElement(“buttonName”);
//set the value
ButtonName.InnerText = “Video Help”;
//create the nodes second child
mlNode url = doc.CreateElement(“url”);
//set the value
url.InnerText = “D:RunHelp.exe”;
// add childes to father
node.AppendChild(ButtonName);
node.AppendChild(url);
// find the node we want to add the new node to
XmlNodeList l = doc.GetElementsByTagName(NodeNameToAddTo);
// append the new node
l[0].AppendChild(node);
// save the file
doc.Save(XmlFilePath);
}

<?xml version=”1.0″?>
<
HelpData xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:xsd=http://www.w3.org/2001/XMLSchema>
<
helpButtonUrls>
<
HelpButtonUrl>
<
buttonName>BugReport</buttonName>
<
url>C:BugRep.exe</url>
</
HelpButtonUrl>
<
HelpButtonUrl>
<
buttonName>Video Help</buttonName>
<
url>D:RunHelp.exe</url>
</
HelpButtonUrl>
</
helpButtonUrls>
</
HelpData>

And that's all there is to it!
Enjoy.
Amit.

Tags :

7 Responses to “How to add a new XML node to file”


  1. vacation

    Said on January 28, 2008 :

    Hi! I’m John Strass and i like your site!
    Thank you!

  2. SAF

    Said on August 9, 2008 :

    Hi buddy,
    Could you help me in this. I have an xml file with the content

    20082999
    1000
    9999
    08/09/2008
    11:58:02

    Now I have to insert an element after outlet or anywere within .

    Hope to hear from you soon.

    Regards
    Ansaf

  3. harsh mittal

    Said on May 26, 2010 :

    thanx budy thats great.

  4. Daniel

    Said on August 23, 2010 :

    Thanks for the walkthrough, had to convert it to vb, but it got the job done for me.

  5. Leonardo

    Said on February 19, 2011 :

    Congratulation ! that was exactly what I was looking for.
    Thanks

  6. Ryan

    Said on March 7, 2011 :

    Thank you alot.

  7. chandan kumar

    Said on May 3, 2012 :

    hello sir, i used your given piece of code but i’m getting error on l[0].AppendChild(node); as OBJECT REFERENCE NOT SET TO An INSTANCE OF AN OBJECT.

    Please help me

    Thanks in advance.

Post a Comment