C# Code Snippets  C# Code Snippets
 C# Code Snippets  C# Code Snippets
 C# Code Snippets  C# Code Snippets
 C# Code Snippets  C# Code Snippets

Wednesday, December 12, 2007

How to add a new XML node to file

Need to open an XML file and add a node?

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>
</
helpButtonUrls>
</
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
XmlNode 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 file after:


<?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 thats all there is to it!



AddThis Social Bookmark Button

5 comments:

Unknown said...

This was a really handy piece of code and solved one of the problems I was trying to work against all night.

I read all over that appending wasn't possible without re-creating the stream, or something like that.

This was a real life saver.

cosmicice said...

I really needed help on xml data read, write and this was a life saver article. Just logged in to so "thnx"

Tom Puleo said...

This is a great, simple example. Thanks! The System.XML namespace isn't always the most intuitive.

BhupalSetti said...

it is really help full to me
thank you for posting article

Unknown said...

thanks :)