How to update XML Node?

It's easy to read the XML file and get the exact Node text, but how do I update Node with a new value?

Think:

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

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 string, node.Update (); does not exist, but this is what I wanted :)

I saw an XmlTextWriter object, but it will write all the XML to a new file, and I just need to update one value in the original Node, I can save it as a new file and then rename the new file to the original name, but ... it should be easier do it right?

How many of you guys have sample code for this?

thanks

+3
source share
4 answers

"" - InnerText . , . , ( , ).

+8

XmlDocument.Load , , .

, XmlDocument.Save, , .

+3

nodeValue node.

node : :

xmlDoc=loadXMLDoc("books.xml");

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

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

+2

node xml- , AFAIK node . .

+1

Source: https://habr.com/ru/post/1702299/


All Articles