tags:

views:

1022

answers:

4

It is easy to read an XML file and get the exact Node Text, but how do I Update that Node with a new value?

To read:

public static String GetSettings(SettingsType type, SectionType section)
{
    XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH));
    XmlDocument document = new XmlDocument();
    document.Load(reader);

    XmlNode node = document.SelectSingleNode(
                        String.Format("/MyRootName/MySubNode/{0}/{1}",
                        Enum.Parse(typeof(SettingsType), type.ToString()),
                        Enum.Parse(typeof(SectionType), section.ToString())));       
    return node.InnerText;
}

to write ...?

public static void SetSettings(SettingsType type, SectionType section, String value)
{
    try
    {
        XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH));
        XmlDocument document = new XmlDocument();
        document.Load(reader);

        XmlNode node = document.SelectSingleNode(
                            String.Format("/MyRootName/MySubNode/{0}/{1}",
                            Enum.Parse(typeof(SettingsType), type.ToString()),
                            Enum.Parse(typeof(SectionType), section.ToString())));
        node.InnerText = value;
        node.Update();
    }
    catch (Exception ex)
    {
        throw new Exception("Error:", ex);
    }
}

Note the line, node.Update(); does not exist, but that's what I wanted :)

I saw the XmlTextWriter object, but it will write the entire XML to a new file, and I just need to update one value in the original Node, I can save as a new file and then rename the new file into the original name but... it has to be simpler to do this right?

Any of you guys have a sample code on about to do this?

Thank you

A: 

XmlDocument.Load has an overload that will take the filename directly so there is no need for the reader.

Similarly when you are done XmlDocument.Save will take a filename to which it will save the document.

AnthonyWJones
No matter if I use the reader or the overload method, I will end up having: "The process cannot access the file 'C:\MyWebsite\appAuthentication.xml' because it is being used by another process."When I use document.WriteTo(writer);
balexandre
or even document.Save(writer);
balexandre
+1  A: 

You don't need an "update" method - setting the InnerText property updates it. However, it only applies the update in memory. You do need to rewrite the whole file though - you can't just update a small part of it (at least, not without a lot of work and no out-of-the-box support).

Jon Skeet
so, even if I use the AppConfig in web.config I will never can save the actual result (text) to the variables, only in memory, is it right Jon?
balexandre
What you mean by "save the actual result to the variables"? Which variables?
Jon Skeet
I'm only able to save the changes "in memory" when I open the xml file I do not see any changes, this is valid to the example in the question and using ConfigurationManager.AppSettings[...] to use <AppConfig> area in web.config file.
balexandre
it is true if I use AppConfig section in Web.Config file only! :)
balexandre
What Jon is saying is that when you load the XML document in question, it loads into memory on the app. Any updates to nodes stay within the in-memory load. It isn't until you write the XML back out to the file, and your application detects the file change, will those changes propagate out to the user.
Dillie-O
A: 

You're updating the node in an in-memory representation of the xml document, AFAIK there's no way to update the node directly in the physical file. You have to dump it all back to a file.

axel_c
A: 

The nodeValue property can be used to change the value of a text node.

The following code changes the text node value of the first element: Example: xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue="Easy Cooking";

source: http://www.w3schools.com/DOM/dom_nodes_set.asp

EvilInside