C# 更新 xml 文件中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2137957/
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-06 23:48:37  来源:igfitidea点击:

Update value in xml file

c#xml

提问by Alexander Stalt

I have a xml-file:

我有一个 xml 文件:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
  <level>
    <node1 />
    <node2 />
    <node3 />
  </level>
</root>

What is the simplest way to insert values in node1, node2, node3 ?

在 node1, node2, node3 中插入​​值的最简单方法是什么?

C#, Visual Studio 2005

C#、Visual Studio 2005

回答by Jeeva Subburaj

//Here is the variable with which you assign a new value to the attribute
    string newValue = string.Empty 
    XmlDocument xmlDoc = new XmlDocument();

    xmlDoc.Load(xmlFile);

    XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
    node.Attributes[0].Value = newValue;

    xmlDoc.Save(xmlFile);

Credit goes to Padrino

归功于Padrino

How to change XML Attribute

如何更改 XML 属性

回答by Rubens Farias

Here you go:

干得好:

XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(@"
    <root>
        <level>
            <node1 />
            <node2 />
            <node3 />
        </level>
    </root>");
XmlElement node1 = xmldoc.SelectSingleNode("/root/level/node1") as XmlElement;
if (node1 != null)
{
    node1.InnerText = "something"; // if you want a text
    node1.SetAttribute("attr", "value"); // if you want an attribute
    node1.AppendChild(xmldoc.CreateElement("subnode1")); // if you want a subnode
}

回答by Aneef

Use AppendChild method to inser a child inside a node.

使用 AppendChild 方法在节点内插入一个子节点。

yournode.AppendChild(ChildNode);

link text

链接文字

回答by Mehmet

XElement t = XElement.Load("filePath");
t.Element("level").Element("node1").Value = "";
t.Element("level").Element("node2").Value = "";
t.Element("level").Element("node3").Value = "";
t.Save("filePath");