C# 更新XML中的嵌套值
我正在尝试编写一个例程来更新XML文件中的值,我相信我已经成功了。下面是XML的一个示例:C# 更新XML中的嵌套值,c#,xml,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"
<?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>
我假设我需要以某种方式连接站点、Id和密钥,但看不到它是如何完成的。使用,如果节点不自动存在,您可以让它创建节点
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);
}
它应该更新到位。你看到了什么行为?请注意,当前您没有在任何地方编写XML或返回XML,因此唯一的检查方法是使用调试器。代码与您的XML不匹配。子体appSettings在您显示的演示XML中没有appSettings的节点。
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);
}