Dotnet总结(4)--xml读写
2024-09-05 20:55:44
供稿:网友
读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;
}