XML文本操作笔记,强制转换错误解决

避免那个XmlElement强制转换错误的方法

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("C:/website/Web.config");
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("/configuration/appSettings").ChildNodes;//获取appSettings节点的所有子节点
            foreach (XmlNode xn in nodeList)//遍历所有子节点
            {
                XmlElement xe = xn as XmlElement;//最好不好用强制转换,建议使用as,这样如果转不过去话,就是null,不会报异常
                if (xe != null)   //这样判断以下是否为null,或者你可以if(xe==null) return ;直接返回或做其他处理
                {
                    string Keyname = xe.Attributes["key"].InnerXml;//键值
                    switch (Keyname)
                    {
                        case "MsgInfo":
                            return xe.Attributes["value"].Value;

                    }
                }
            }
            return "";

posted @ 2009-09-23 16:07  Zoya Qiu  阅读(206)  评论(0编辑  收藏  举报