如何使用C#仅修改XML文件的选择参数/属性?

时间:2013-10-30 08:31:11

标签: c# .net xml

说,如果我有一个任意的XML文件,有没有办法只修改某个参数/属性而不更改XML文件的其余部分?例如,让我们举一个简单的例子:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- The xml file itself contains many other tags -->
  <ConfigSection>
    <GeneralParams>
      <parameter key="TableName" value="MyTable1" />
    </GeneralParams>
  </ConfigSection>
</configuration>

如何将密钥TableName的值更新为&#34; MyTable2&#34;?

2 个答案:

答案 0 :(得分:1)

不确定这是最好的方法,但试一试。

string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
        <configuration>
          <!-- The xml file itself contains many other tags -->
          <ConfigSection>
            <GeneralParams>
              <parameter key=""TableName"" value=""MyTable1"" />
            </GeneralParams>
          </ConfigSection>
        </configuration>";

var xdoc = XDocument.Parse(xml);
xdoc.Descendants("parameter")
    .Single(x => x.Attribute("key").Value == "TableName" && x.Attribute("value").Value == "MyTable1")
    .Attributes("value").First().Value = "MyTable2";

答案 1 :(得分:1)

还有另一种使用XmlDocument的方式。

            string xml = @"<?xml version='1.0' encoding='UTF-8'?>
                            <configuration>
                              <ConfigSection>
                                <GeneralParams>
                                  <parameter key='TableName' value='MyTable1' />
                                </GeneralParams>
                              </ConfigSection>
                            </configuration>";

            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(xml);

            XmlNode paramter;
            XmlNode root = xDoc.DocumentElement;

            paramter = xDoc.SelectSingleNode("//parameter/@key");
            paramter.LastChild.InnerText = "MyTable2";

            string modifiedxml = xDoc.OuterXml;