How to update XML nodes with new values?

亡梦爱人 提交于 2019-12-21 05:17:04

问题


I have a xml inside my App_Data folder. I need to edit the values in nodes of that xml. What I had tried is-

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(Server.MapPath("~/App_Data/conf.xml.config"));

        XmlNodeList aNodes = xDoc.SelectNodes("/ConfigInf");
        foreach (XmlNode node in aNodes)
        {
            XmlNode child1 = node.SelectSingleNode("Node1");
            XmlNode child2 = node.SelectSingleNode("Node2");              

            child1.InnerText = "Value1";
            child2.InnerText = "Value2";
        }

I need to re-write the xml with new values as when ever I try to access the same xml again, it should contain the new values. But when I access the xml, I still get the old(initial) values only when I call like this -Test.LoadConf(Server.MapPath("./App_Data/conf.xml.config"));. How to write to XML with new values or any alternative method like create a new xml with new values?(as I need to access this xml in a single page only)


回答1:


call save after edit, you can give diferent name if you don't need to overwrite the original

e.g. new file named as new.conf.xml.config

xDoc.Save(Server.MapPath("~/App_Data/new.conf.xml.config"));

next time you can load the original as usual

xDoc.Load(Server.MapPath("~/App_Data/conf.xml.config"));



回答2:


You haven't saved the file after that

use xDoc.save(Server.MapPath("~/App_Data/conf.xml.config"));




回答3:


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




回答4:


node["Node1"].InnerText = "Value1";
node["Node2"].InnerText = "Value2";


来源:https://stackoverflow.com/questions/16806838/how-to-update-xml-nodes-with-new-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!