Reputation: 5866
I am trying to update a simple xml file with XDocument. here is my simple xml file
<?xml version="1.0" encoding="utf-8" ?>
<message>Test test test test</message>
thats xml above.
when the user clicks the Button1, it reads the xml and display it on the screen. But when u click the Button2, it doesnt update the xml.
public partial class www_html_test : System.Web.UI.Page
{
XDocument doc;
XElement elem;
protected void Page_Load(object sender, EventArgs e)
{
doc = XDocument.Load(Server.MapPath("xml/test.xml"));
elem = doc.Element("message");
}
protected void Button1_Click(object sender, EventArgs e)
{
try{
Label1.Text = elem.Value.ToString();
} catch(Exception ex){
Label1.Text = ex.Message;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try{
elem.Value = "test 2 test 2 test 2";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
How can I update the xml?
Upvotes: 0
Views: 945
Reputation: 609
Change the button 2 click event handler to
protected void Button2_Click(object sender, EventArgs e)
{
try{
elem.Value = "test 2 test 2 test 2";
doc.Save(Server.MapPath("xml/test.xml"));
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Upvotes: 1
Reputation: 11025
You need to call doc.Save(Server.MapPath("xml/test.xml"))
.
At the point you change the elem
value, it's only in memory. To commit to disk, you must Save.
Upvotes: 1