Search code examples
asp.netxmlxmlreaderxmltextreader

How to parse and update xml file using xmltextreader or xmlreader


Hi i have the following code to read the xml file and change the value of particular node ,but i want to do the same using xmltextreader or xmlreader, i am trying to avoid the statement doc.Save(System.Web.HttpContext.Current.Server.MapPath("Data/Example.xml")); , which has a direct reference to my physical file.

XmlDocument doc = new XmlDocument();
                   string xmlFile = System.Web.HttpContext.Current.Server.MapPath("Data/Example.xml");
                   doc.Load(xmlFile);
                   XmlNodeList xmlnode = doc.GetElementsByTagName("value");
                   xmlnode[0].ChildNodes[0].Value = 23;
 doc.Save(System.Web.HttpContext.Current.Server.MapPath("Data/Example.xml"));

Solution

  • Well something's going to have to have a reference to the file. However, you could easily change your code to simply accept a Stream (which would have to be readable, writable and seekable):

    private static void ChangeDocument(Stream stream)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(stream);
        XmlNodeList xmlnode = doc.GetElementsByTagName("value");
        xmlnode[0].ChildNodes[0].Value = 23;
        stream.Position = 0;
        doc.Save(stream);
        stream.SetLength(stream.Position); // Truncate the file if it was longer
    }
    

    It's somewhat ugly, admittedly...

    Of course you could always pass in the filename itself - your MapPath call would still be in a higher level method, which may be all you're trying to achieve:

    private static void ChangeDocument(string filename)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(filename);
        XmlNodeList xmlnode = doc.GetElementsByTagName("value");
        xmlnode[0].ChildNodes[0].Value = 23;
        doc.Save(filename);
    }
    

    One final aside - if you're using .NET 3.5 or higher, I'd strongly recommend using LINQ to XML as a rather nicer XML API.