Wednesday, July 1, 2009

How to Insert a new Node in XML File in C#

This is 4th post regarding XML. In this, I will teach you how to insert a new node in XML file.

The sample XML file is shown below which is before Inserting new Node.

<?xml version="1.0"?>
<Library>
<Subjects name="Computer Science">
<Publishers name="Wrox">
<Begginers>Beginning C#</Begginers>
</Publishers>
</Subjects>
</Library>


Now write the below code to insert a new node in XML.

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(filename);
//Create New Element
XmlElement element = xmldoc.CreateElement("Begginers");
element.InnerText = "BEGINNER C# (INDIAN WRITER)";
//Insert Node after Publishers
xmldoc.DocumentElement["Subjects"].ChildNodes[0].InsertAfter(element, xmldoc.DocumentElement["Subjects"].ChildNodes[0].LastChild);
FileStream fsxml = new FileStream(filename, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
xmldoc.Save(fsxml);
Console.WriteLine("XML Updated Successfully");


After executing this code you will get the following output.

<?xml version="1.0"?>
<Library>
<Subjects name="Computer Science">
<Publishers name="Wrox">
<Begginers>Beginning C#</Begginers>
<Begginers>BEGINNER C# (INDIAN WRITER)</Begginers>
</Publishers>
</Subjects>
</Library>

No comments: