我在做安装程序时,增加了个类,来还原数据库及修改webconfig的数据库连接,代码如下:
protected void ModXML()
{
string sXMLPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName + @"\web.config";
FileInfo XMLFile = new FileInfo(sXMLPath);
if (XMLFile.Exists == false)
MessageBox.Show("没有找到配置文件,请你手动增加!");
else
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(sXMLPath);
XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
foreach (XmlElement element in topM)
{
if (element.Name.ToLower() == "appsettings")
{
XmlNodeList _node = element.ChildNodes;
foreach (XmlElement el in _node)
{
if (el.Attributes["key"].InnerXml == "ConnectString")
{
el.Attributes["value"].Value = string.Format("user id={0};pwd=;data source={1};initial catalog=FileManage;Connection Reset=false", sUserID, sServerName);
}
}
}
}
xmldoc.Save(sXMLPath);
}
}当我制作好安装程序,安装时却出现:无法将类型为"System.Xml.XmlComment"的对象强制转化为"System.Xml.XmlElement".
真奇怪!!!!!!!!!!!!!!!
protected void ModXML()
{
string sXMLPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName + @"\web.config";
FileInfo XMLFile = new FileInfo(sXMLPath);
if (XMLFile.Exists == false)
MessageBox.Show("没有找到配置文件,请你手动增加!");
else
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(sXMLPath);
XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
foreach (XmlElement element in topM)
{
if (element.Name.ToLower() == "appsettings")
{
XmlNodeList _node = element.ChildNodes;
foreach (XmlElement el in _node)
{
if (el.Attributes["key"].InnerXml == "ConnectString")
{
el.Attributes["value"].Value = string.Format("user id={0};pwd=;data source={1};initial catalog=FileManage;Connection Reset=false", sUserID, sServerName);
}
}
}
}
xmldoc.Save(sXMLPath);
}
}当我制作好安装程序,安装时却出现:无法将类型为"System.Xml.XmlComment"的对象强制转化为"System.Xml.XmlElement".
真奇怪!!!!!!!!!!!!!!!
foreach (XmlElement el in _node)
foreach(XmlNode in _node )
{
先判断一下_nodd的类型.}
{
先判断一下node的类型.}
{
先判断一下node的类型.}
说清楚点,我不明白
所以根据他的父类型来遍历比较安全,在遍历中先判断是不是xmlElement,再操作.
所以根据他的父类型来遍历比较安全,在遍历中先判断是不是xmlElement,再操作.
--------------------
不知道怎么做,你写出来吧,谢谢了
foreach (XmlNode node in _node)
{
if( node.GetType() == typeof(System.Xml.XmlElement))
{
XmlElement el = (XmlElement)node;
if (el.Attributes["key"].InnerXml == "ConnectString")
{
el.Attributes["value"].Value = string.Format("user id={0};pwd=;data source={1};initial catalog=FileManage;Connection Reset=false", "dddddddd", "BdddddddB");
}
}
}