Wednesday, July 1, 2009

How to Insert an New Element in XML File in C#

This is my third post in which I tell you how to Insert an Element in XML file.

The sample XML file is shown below

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


Now you write the code to insert a new Element.

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(filename);
//New XML ELEMENT Created
XmlElement xElement = xmldoc.CreateElement("Publishers");

//NEW XML ATTRIBUTE Created
XmlAttribute xAttribute = xmldoc.CreateAttribute("name");
xAttribute.Value = "Indian Book";
xElement.SetAttributeNode(xAttribute);

//Create Inner Element
XmlElement element = xmldoc.CreateElement("Begginers");
element.InnerText = "BEGINNER C# (INDIAN WRITER)";
xElement.AppendChild(element);
xmldoc.DocumentElement.InsertAfter(xElement, xmldoc.DocumentElement.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.

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

No comments: