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>

11 comments:

  1. can u tell me how to remove a particuler item here ?

    ReplyDelete
  2. Doesn't work, at least for me, it throws "NullReference" errors

    ReplyDelete
  3. I cant add my problem here as it says the html cannot be accepted
    do you have a email i can send to

    my email is mannbik@gmail.com
    Thanks

    ReplyDelete
  4. SEARCH AND EDIT XML FILE USING C#
    ................................
    PLZ SEND MY MAIL ID

    ms9790448636@gmail.com

    Suresh M

    ReplyDelete
  5. Kudos! Kavitha

    Please post more solutions

    Thanks once again

    Sunkara

    ReplyDelete
  6. Add save method after AppendChile(xItem);

    eg:
    xDoc.DocumentElement.LastChild.AppendChild(xItem);
    xDoc.Save(fileName);
    then it will save the File with new Chages

    ReplyDelete