更新xml文件中的值

时间:2010-01-26 07:13:13

标签: c# xml

我有一个xml文件:

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

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

C#,Visual Studio 2005

4 个答案:

答案 0 :(得分:5)

你走了:

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
}

答案 1 :(得分:3)

//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);

归功于Padrino

How to change XML Attribute

答案 2 :(得分:0)

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");

答案 3 :(得分:-1)

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

yournode.AppendChild(ChildNode);

link text