Showing posts with label Append new Node in Xml File. Show all posts
Showing posts with label Append new Node in Xml File. Show all posts

Tuesday, July 28, 2009

Append new Node in Xml File

Append new Nod in Existing xml File


Suppose we have an xml like this -XMLFile6.xml

<?xml version="1.0"?>
<items>
<item>
<title>wewewe</title>
<itemid>regdoc</itemid>
<summary>fvdfv</summary>
<body>vf</body>
<image>default.jpg</image>
<author>dddd</author>
<date>2009-02-02 14:26:00.0</date>
</item>
</items>

Here i want to add one more node Item below Items.. then we can do it using the xmlDom.
as following.

string fileName = Server.MapPath("XMLFile6.xml");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fileName);

string strNewNodeToInsert = " <item>" +
"<title>wewewe</title>" +
"<itemid>regdoc</itemid>" +
"<summary>fvdfv</summary>" +
"<body>vf</body>" +
"<image>default.jpg</image>" +
"<author>dddd</author>" +
"<date>2009-02-02 14:26:00.0</date>" +
"</item>";



XmlNode xItem = xDoc.CreateElement("item");

XmlNode xTitle = xDoc.CreateElement("title");
xTitle.InnerText = "kavs";

XmlNode xItemid = xDoc.CreateElement("itemid");
xItemid.InnerText = "itemid";

XmlNode xSummary = xDoc.CreateElement("summary");
xSummary.InnerText = "summary";

//and so on for author and date

xItem.AppendChild(xTitle);
xItem.AppendChild(xItemid);
xItem.AppendChild(xSummary);

xDoc.DocumentElement.LastChild.AppendChild(xItem);


It will give me output as

<?xml version="1.0"?>
<items>
<item>
<title>wewewe</title>
<itemid>regdoc</itemid>
<summary>fvdfv</summary>
<body>vf</body>
<image>default.jpg</image>
<author>dddd</author>
<date>2009-02-02 14:26:00.0</date>
</item>
<item>
<title>wewewe</title>
<itemid>regdoc</itemid>
<summary>fvdfv</summary>
<body>vf</body>
<image>default.jpg</image>
<author>dddd</author>
<date>2009-02-02 14:26:00.0</date>
</item>
</items>