0

比如说,如果我有一个任意 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“MyTable2”?

4

2 回答 2

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";
于 2013-10-30T08:39:31.850 回答
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;
于 2013-10-30T08:59:14.430 回答