2014-10-28 62 views
0

我正在尝试编写一个更新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和密钥,但是看不到它是如何完成的。

+0

它应该在原地更新。你看到什么行为?请注意,目前您不是在任何地方编写XML或将其返回,因此唯一的方法是使用调试器进行检查。 – Dweeberly 2014-10-28 18:34:41

+1

代码与您的XML不匹配。 '后代(“appSettings”)'你演示的XML中没有'appSettings'节点。 – 2014-10-28 18:36:13

回答

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