how to read and update an xml file

I have an xml file with the follow fields:
<name> John Doe </name>
<city> XYZ </city>
<zip> 88888 </zip>


How can i update for example the zip code to 99999 without affecting other fields


Answer this question

how to read and update an xml file

  • &amp;#42;Jinx

    As long as there is a zip element then SelectSingleNode("//zip") will find that and return an element node on which you can set the InnerText as described earlier.

    If you don't have any zip element then you can create one and insert it where you want to insert it e.g.

    XmlDocument xmlDocument = new XmlDocument();

    xmlDocument.Load(@"file.xml");

    XmlElement zip = xmlDocument.CreateElement("zip");

    zip.InnerText = "99999";

    // appending to root element for this example

    // in general call appendChild on the node you want to append to

    xmlDocument.DocumentElement.AppendChild(zip);

    This sample is probably not what you finally need for your sample XML but you have not shown us what the parent and ancestor elements of your name, city, zip elements are so for now I have simply shown how to append to the root element. The creation of the element however is always done as shown, only you will probably append then to a child or descendant of the root element. That element you want to append to can of course also be found with XPath and SelectSingleNode.



  • kevin D. white

    AFAIK, you have to read the entire xml file and then re-write the part you want to edit. If you serialized the xml file, then you can easily update it since serialization/deserialization usually takes/puts things into/from a collection for example (restores them) then you could just serialize the collection back to xml without worrying too much about reading the xml file and re-writing the node/attribute, after modifying the object in the collection.

    I could be wrong however but would be advisable to use serialization.



  • Rajwebdev

    Use System.Xml.XmlDocument and load the XML. Then you can use XPath with SelectSingleNode or SelectNodes to find nodes (e.g. //zip) and e.g. elementNode.InnerText = "99999" to change the contents of an element node found.

  • Mateusz Rajca

    What would happen if the config file is set up but there's no value inside the node yet like
    <name>John Doe </name>
    <city>XYZ</city>
    <zip/>

    if i do elementNode.InnerText = "99999" won't work since elementNode is null. how can i take care of this case


  • Tom Hartnett

    cool, thats great!

  • how to read and update an xml file