Lou*_*hys 5 .net c# xml app-config
通过appSettings-like我的意思是这样的,
<appSettings>
<add key="myKey" value="myValue" />
</appsettings>
Run Code Online (Sandbox Code Playgroud)
结果是我可以访问的键值集合,如:
string v = config["myKey"];
Run Code Online (Sandbox Code Playgroud)
但它不一定位于app.config中,所以我拥有的是字符串或XmlNode.
NameValueFileSectionHandler.Create方法显然可以完成这项工作,但输入需要两个对象,Object parent,Object configContext,以及xml节点,我不知道传递给它们的内容.
将字符串解析为这样的字典,
var xml = XElement.Parse("<appSettings><add key=\"myKey\" value=\"myValue\" /></appSettings>");
var dic = xml.Descendants("add").ToDictionary(x => x.Attribute("key").Value, x => x.Attribute("value").Value);
Run Code Online (Sandbox Code Playgroud)
你可以得到这样的值,
var item = dic["myKey"];
Run Code Online (Sandbox Code Playgroud)
您也可以像这样修改字典中的值,
dic["myKey"] = "new val";
Run Code Online (Sandbox Code Playgroud)
您可以使用此代码将修改后的字典转换回XElement,
var newXml = new XElement("appSettings", dic.Select(d => new XElement("add", new XAttribute("key", d.Key), new XAttribute("value", d.Value))));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2204 次 |
| 最近记录: |