主要源代码:
private XmlDocument myXmlDoc;
private
void
initXmlDoc()
{
this .myXmlDoc = new XmlDocument();
string docPath = Server.MapPath( " ~/. " + " / " + " web.config " );
myXmlDoc.Load(docPath);
}
private void replaceXmlNodeValue( String XName,String XAttrKey,String XAttrValue,String XNAttrKey,String XNValue )
{
XmlNode myNode = this .myXmlDoc.DocumentElement.SelectSingleNode( " descendant:: "
+ XName + " [@ " + XAttrKey + " =' " + XAttrValue + " '] " );
myNode.Attributes[XNAttrKey].Value = XNValue;
}
private bool reNewConfig( XmlDocument newXmlDoc )
{
bool returnValue = true ;
String docPath = Server.MapPath( " ~/. " + " / " + " web.config " );
XmlTextWriter myWriter = new XmlTextWriter( docPath , this .Page.Response.ContentEncoding );
try
{
newXmlDoc.WriteContentTo( myWriter );
}
catch
{
returnValue = false ;
}
finally
{
myWriter.Close();
}
return returnValue;
}
{
this .myXmlDoc = new XmlDocument();
string docPath = Server.MapPath( " ~/. " + " / " + " web.config " );
myXmlDoc.Load(docPath);
}
private void replaceXmlNodeValue( String XName,String XAttrKey,String XAttrValue,String XNAttrKey,String XNValue )
{
XmlNode myNode = this .myXmlDoc.DocumentElement.SelectSingleNode( " descendant:: "
+ XName + " [@ " + XAttrKey + " =' " + XAttrValue + " '] " );
myNode.Attributes[XNAttrKey].Value = XNValue;
}
private bool reNewConfig( XmlDocument newXmlDoc )
{
bool returnValue = true ;
String docPath = Server.MapPath( " ~/. " + " / " + " web.config " );
XmlTextWriter myWriter = new XmlTextWriter( docPath , this .Page.Response.ContentEncoding );
try
{
newXmlDoc.WriteContentTo( myWriter );
}
catch
{
returnValue = false ;
}
finally
{
myWriter.Close();
}
return returnValue;
}
调用 :
String DBConnectionString
=
"
server={0};database={1};UID={2};Password={3}
"
;
String newDBCntString = String.Format(
DBConnectionString, this .txtDBIP.Text.Trim(), this .txtDBName.Text.Trim(),
this .txtDBUser.Text.Trim(), this .txtDBPwd.Text.Trim() );
this .initXmlDoc();
// <add key="ConnectionString" value="server=(local);database=Pedu;UID=sa;Password=sa" />
this .replaceXmlNodeValue( " add " , " key " , " ConnectionString " , " value " ,newDBCntString );
this .reNewConfig( this .myXmlDoc );
String newDBCntString = String.Format(
DBConnectionString, this .txtDBIP.Text.Trim(), this .txtDBName.Text.Trim(),
this .txtDBUser.Text.Trim(), this .txtDBPwd.Text.Trim() );
this .initXmlDoc();
// <add key="ConnectionString" value="server=(local);database=Pedu;UID=sa;Password=sa" />
this .replaceXmlNodeValue( " add " , " key " , " ConnectionString " , " value " ,newDBCntString );
this .reNewConfig( this .myXmlDoc );