Directory Freebies VS CheatSheet Forum

RSS

Email

Translate

Home About Archive Privacy Contact Advertise Write for Dev102
Posted by Amit on Dec 12th, 2007 | Filed under C# |

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

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


  1. vacation Said on Jan 28, 2008 :

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

  2. SAF Said on Aug 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

Post a Comment

Write Article for Dev102

Write for Dev102!

We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution

Learn More