Dec
12th | 2007

How to add a new XML node to file

Filed under C# | Posted by Amit

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: , ,

One Response to “How to add a new XML node to file”



  1. By vacation on Jan 28, 2008 | Reply

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

Post a Comment

Search Dev102