C# 如何使用新值更新 XML 节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16806838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:49:16  来源:igfitidea点击:

How to update XML nodes with new values?

c#asp.netxmlxmldocumentxmlnode

提问by Sandy

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

我的App_Data文件夹中有一个 xml 。我需要编辑该 xml 节点中的值。我试过的是——

        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)

我需要用新值重新编写 xml,因为当我再次尝试访问相同的 xml 时,它应该包含新值。但是当我访问 xml 时,只有当我这样调用时,我仍然会得到旧的(初始)值 - Test.LoadConf(Server.MapPath("./App_Data/conf.xml.config"));。如何使用新值或任何替代方法写入 XML,例如使用新值创建新 xml?(因为我只需要在单个页面中访问此 xml)

采纳答案by Damith

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

编辑后调用save,如果不需要覆盖原来的可以给不同的名字

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

例如新文件命名为 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"));

回答by Taj

You haven't saved the file after that

之后你还没有保存文件

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

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

回答by Saurabh

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

nodeValue 属性可用于更改文本节点的值。

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

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

回答by Mohan Krishna Eluri

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