读xml,
public static string ReadXMLConfig(string strFileName, string sKey)
{
// string strFileName = "Brand.exe.config";
XmlDocument oXmlDocument = new XmlDocument();
string strReturn="";
try
{
oXmlDocument.Load(Application.StartupPath+"\\"+strFileName);
XmlNodeList oXmlNodeList = oXmlDocument.DocumentElement.ChildNodes;
foreach (XmlElement oXmlElement in oXmlNodeList)
{
if (oXmlElement.Name.ToLower() == "appsettings")
{
XmlNodeList _node = oXmlElement.ChildNodes;
if (_node.Count > 0)
{
foreach (XmlElement _el in _node)
{
if (_el.Attributes["key"].InnerXml.ToLower() == sKey.ToLower())
{
strReturn = _el.Attributes["value"].Value;
break;
}
}
}
}
}
}
catch (Exception exp)
{
if (sKey.ToLower() == "dsn")
{
strReturn = "Connect Timeout=5;server=localhost;database=Brand;uid=sa;pwd=";
}
XmlTextWriter oXmlTextWriter = new XmlTextWriter(strFileName, new System.Text.UTF8Encoding());
oXmlTextWriter.WriteStartDocument();
oXmlTextWriter.WriteStartElement("configuration");
oXmlTextWriter.WriteStartElement("appSettings");
oXmlTextWriter.WriteStartElement("add");
oXmlTextWriter.WriteAttributeString("key", sKey);
oXmlTextWriter.WriteAttributeString("value", strReturn);
oXmlTextWriter.WriteEndElement();
oXmlTextWriter.WriteEndElement();
oXmlTextWriter.WriteEndElement();
oXmlTextWriter.WriteEndDocument();
oXmlTextWriter.Close();
}
return strReturn;
}
// 写
private string WriteWebConfig(string sKey, string sValue)
{
string strFileName = "Brand.exe.config";
XmlDocument oXmlDocument = new XmlDocument();
try
{
oXmlDocument.Load(strFileName);
XmlNodeList oXmlNodeList = oXmlDocument.DocumentElement.ChildNodes;
foreach (XmlElement oXmlElement in oXmlNodeList)
{
if (oXmlElement.Name.ToLower() == "appsettings")
{
XmlNodeList _node = oXmlElement.ChildNodes;
if (_node.Count > 0)
{
foreach (XmlElement _el in _node)
{
if (_el.Attributes["key"].InnerXml.ToLower() == sKey)
{
_el.Attributes["value"].Value = sValue;
break;
}
}
}
}
}
}
catch
{
return "";
}
oXmlDocument.Save(strFileName);
return sValue;
}
本文地址:http://com.8s8s.com/it/it41292.htm