You must specify the absolute path to the file using MapPath () in order to save the XML document and not increase the tag name, for example comment1, comment2 .., etc.
Take a look at the code snippet:
protected void Button1_Click(object sender, EventArgs e) { string file = MapPath("~/comments.xml"); XDocument doc; //Verify whether a file is exists or not if (!System.IO.File.Exists(file)) { doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new System.Xml.Linq.XElement("comments")); } else { doc = XDocument.Load(file); } XElement ele = new XElement("comment",TextBox1.Text); doc.Root.Add(ele); doc.Save(file); }
EDIT: if you want to insert the <comment>
into an existing xml document, then you do not need to create an XDocument. Just upload an existing document and add a new item to the root directory.
protected void Button1_Click(object sender, EventArgs e) { string file = MapPath("~/myxmlfile.xml"); XDocument doc = XDocument.Load(file); XElement ele = new XElement("comment",TextBox1.Text); doc.Root.Add(ele); doc.Save(file); }
To add another <comment>
inside <comment>
:
XElement ele = new XElement("comment",TextBox1.Text); doc.Root.Element("comment").Add(ele); doc.Save(file);
To replace the text value of the <comment>
:
doc.Root.Element("comment").Value = TextBox1.Text; //doc.Root.Element("comment").Value += TextBox1.Text; //append text doc.Save(file);
XML document:
<?xml version="1.0" encoding="utf-8" ?> <comments> <comment>First Child</comment> <comment> <comment>Nested</comment> </comment> </comments>
source share