Tuesday, February 23, 2010

Adding New Node to an Existing XML file

We have an XML file named: TestXML.xml

Structure is as follow:




We wanted to add a new node.

This code block will do the same

public void AddXMLNode(string XMLFilePath,string TitleToAdd, string ArtistToAdd)
{
XmlDocument doc = new XmlDocument();
doc.Load(XMLFilePath);
XmlNode node = doc.CreateNode(XmlNodeType.Element, "CD", null);
XmlNode TitleNode = doc.CreateElement("title");
TitleNode.InnerText = TitleToAdd;
XmlNode ArtistNode = doc.CreateElement("artist");
ArtistNode.InnerText = ArtistToAdd;
node.AppendChild(TitleNode);
node.AppendChild(ArtistNode);
XmlNodeList list = doc.GetElementsByTagName("Catalog");
list[0].AppendChild(node);
doc.Save(XMLFilePath);
}

Now Test This Code:

AddXMLNode(TestXML.xml,”Deewana”,”Sonu Nigam”);

Now the Structure Will Look Like:



Enjoy...

No comments:

Post a Comment