0
点赞
收藏
分享

微信扫一扫

设置配置文件的某个节点的值


public static void SetConnectionStringsKeyValue(string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;

xNode = xDoc.SelectSingleNode("//connectionStrings");

xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@name='" + AppKey + "']");
if (xElem1 != null) xElem1.SetAttribute("connectionString", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("name", AppKey);
xElem2.SetAttribute("connectionString", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}

public static void SetAppSettingsKeyValue(string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;

xNode = xDoc.SelectSingleNode("//appSettings");

xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}

配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="" />
</connectionStrings>

<appSettings>
<add key="AdminPwd" value=""/>
<add key="GridAlterRowBackColor" value="-2627631"/>
</appSettings>

<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>

</configuration>

读取某个值:

static int GetGridSetting()
{
int iReadColor = 0;
object oResult = System.Configuration.ConfigurationManager.AppSettings["GridAlterRowBackColor"];
if (!Common.IsNullOrEmptyObject(oResult))
{
iReadColor = Convert.ToInt32(oResult.ToString());
}

return iReadColor;
}

public static bool IsNullOrEmptyObject(object oSource)
{
if (oSource != null)
{
return string.IsNullOrEmpty(oSource.ToString());
}
return true;
}


XML操作总结

c# 读取xml某个节点的值的方法

​​http://shirlly.iteye.com/blog/414203​​

C# 读取XML文件某个节点的值


举报

相关推荐

0 条评论