How to update an XML file (read and write)

Hi all,

I have the code to read values in an XML file:
XmlTextReader tr = new XmlTextReader(filename);
while (tr.Read())
{
if (tr.NodeType == XmlNodeType.Element)
{
tr.Read(); ...

Now I want to update some values in this XML file and save it.

I need to change the read only access to write access. I already try XmlTextWriter, but it didn't work well.

Can anybody send me a very simple sample code in C# to do it

Thanks a ot in advance,

Bertrand




Answer this question

How to update an XML file (read and write)

  • Dr.Virusi

    You cannot simultaneously read and write to the same file. You may:

    • read the xml file into XmlDocument, close the reader, update the document, save it to the same filename.
    • open the reader from filename and xmltextwriter to a temp file, do read and write with two different files, after you close both reader and writer, move the temp file over the input file.

    I hope this answers your question.



  • crazy_boss

    ouah....not sure I like this approach.

    I just want to replace one field in my XML file. Can I open it, read and search the word I want to replace. Add the new value and save the document and close it

    Your idea is good but seems very time and resource consuming if I only want to do a real update.

    Also, if you could write some code that shows how to open the Writer and proceed the Update().

    Thanks,

    B.



  • adam99

    XmlWriter can be created with XmlWriter.Create("FileName.xml")

    See http://msdn2.microsoft.com/en-us/library/system.xml.xmlwriter_methods(VS.80).aspx.

    Simplest approch for you would be to use XmlDocument:

    XmlDocument doc = new XmlDocument();

    doc.Load("FileName.xml");

    // Edit doc ...

    doc.Save("FileName.xml");

    See http://msdn2.microsoft.com/en-us/library/system.xml.xmldocument.aspx.



  • How to update an XML file (read and write)