更新XML中的嵌套值

时间:2014-10-28 18:26:16

标签: c# xml

我正在尝试编写一个更新XML文件中的值的例程,并相信我已经接近了。这是XML的一个例子:

        <?xml version="1.0" encoding="utf-8"?>
<!-- This file is generated by the GPS_Client program. -->
<Sites>
  <Site>
    <Id>A</Id>
    <add key="landingName" value="Somewhere" />
    <add key="landingLat" value="47.423719" />
    <add key="landingLon" value="-123.011364" />
    <add key="landingAlt" value="36" />
  </Site>
  <Site>
    <Id>B</Id>
    <add key="landingName" value="Somewhere Else" />
    <add key="landingLat" value="45.629160" />
    <add key="landingLon" value="-128.882934" />
    <add key="landingAlt" value="327" />
  </Site>
</Sites>

关键是我需要更新特定密钥而不更新其他具有相同名称的密钥。这是当前的代码:

        private void UpdateOrCreateAppSetting(string filename, string site, string key, string value)
{
    string path = "\"@" + filename + "\""; 
    XDocument doc = XDocument.Load(path); 
    var list = from appNode in doc.Descendants("appSettings").Elements()
            where appNode.Attribute("key").Value == key
            select appNode;
    var e = list.FirstOrDefault();

    // If the element doesn't exist, create it
    if (e == null) {
        new XElement(site,
            new XAttribute(key, value));
    // If the element exists, just change its value
    } else {
        e.Element(key).Value = value; 
        e.Attribute("value").SetValue(value);
    }
}

我认为我需要以某种方式连接网站,ID和密钥,但不知道它是如何完成的。

1 个答案:

答案 0 :(得分:0)

使用this XmlLib,如果节点不自动存在,您可以创建节点。

private void UpdateOrCreateAppSetting(string filename, string site, 
                                      string key, string value)
{
    string path = "\"@" + filename + "\""; 
    XDocument doc = XDocument.Load(path);
    XPathString xpath = new XPathString("//Site[Id={0}]/add[@key={1}]", site, key);
    XElement node = doc.Root.XPathElement(xpath, true); // true = create if not found
    node.Set("value", value, true); // set as attribute, creates attribute if not found
    doc.Save(filename);
}