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>
Its Nice and Simple
ReplyDeleteThanks Kavs
J
can u tell me how to remove a particuler item here ?
ReplyDeleteDoesn't work, at least for me, it throws "NullReference" errors
ReplyDeleteI cant add my problem here as it says the html cannot be accepted
ReplyDeletedo you have a email i can send to
my email is mannbik@gmail.com
Thanks
SEARCH AND EDIT XML FILE USING C#
ReplyDelete................................
PLZ SEND MY MAIL ID
ms9790448636@gmail.com
Suresh M
Kudos! Kavitha
ReplyDeletePlease post more solutions
Thanks once again
Sunkara
Add save method after AppendChile(xItem);
ReplyDeleteeg:
xDoc.DocumentElement.LastChild.AppendChild(xItem);
xDoc.Save(fileName);
then it will save the File with new Chages
Thanks venugopal
DeleteThank you.
ReplyDeletethanks for your code...
ReplyDeletemaza ni aya
ReplyDelete