0

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?

1
  • 1
    How do you know it isn't updating the xml? I don't see you writing the value back to the page or saving the xml file after changing the value. Commented Jun 18, 2013 at 16:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
        }
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.