我在做安装程序时,增加了个类,来还原数据库及修改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".
真奇怪!!!!!!!!!!!!!!!

解决方案 »

  1.   

    XmlNodeList _node = element.ChildNodes;
                            foreach (XmlElement el in _node)
    foreach(XmlNode in _node )
    {
     先判断一下_nodd的类型.}
      

  2.   

    foreach(XmlNode node in _node )
    {
     先判断一下node的类型.}
      

  3.   

    foreach(XmlNode node in _node )
    {
     先判断一下node的类型.}
    说清楚点,我不明白
      

  4.   

    XmlNodeList _node = element.ChildNodes因为 _node中的所有node不一定都是 XmlElement ,为什么报错就是因为遇到了XmlComment
    所以根据他的父类型来遍历比较安全,在遍历中先判断是不是xmlElement,再操作.
      

  5.   

    XmlNodeList _node = element.ChildNodes因为 _node中的所有node不一定都是 XmlElement ,为什么报错就是因为遇到了XmlComment
    所以根据他的父类型来遍历比较安全,在遍历中先判断是不是xmlElement,再操作.
    --------------------
    不知道怎么做,你写出来吧,谢谢了
      

  6.   

    XmlNodeList _node = element.ChildNodes;
                        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");
                                }
                           }
                        }