winforms 无法将类型为“System.Xml.XmlComment”得对象强制转换为类型为“System.Xml.XmlElement.”

cuxqih21  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(288)

我有一个Winform应用程序,我得到以下错误。你能帮我解决它吗?

public class ChangeLanguage
    {
        public void UpdateConfig(string key, string value)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            foreach (XmlElement xmlElement in xmlDoc.DocumentElement)
            {
                if (xmlElement.Name.Equals("appSettings"))
                {
                    foreach (XmlNode xNode in xmlElement.ChildNodes)
                    {
                        if (xNode.Attributes[0].Value.Equals(key))
                        {
                            xNode.Attributes[1].Value = value;
                        }
                    }
                }
            }

            ConfigurationManager.RefreshSection("appSettings");

            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }
    }
}
xdnvmnnf

xdnvmnnf1#

存在转换错误。如果只想对XmlElement对象进行迭代和执行某些操作,则必须使用OfType检查该类型(因为没有可用的linq)。在示例中,解决方案可能如下所示:

public class ChangeLanguage
{
    public void UpdateConfig(string key, string value)
    {
        var xmlDoc = new XmlDocument();
        xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

       foreach (var xmlElement in xmlDoc.DocumentElement.OfType<XmlElement>())
       {
            if (xmlElement.Name.Equals("appSettings"))
            {
                foreach (XmlNode xNode in xmlElement.ChildNodes)
                {
                    if (xNode.Attributes[0].Value.Equals(key))
                    {
                        xNode.Attributes[1].Value = value;
                    }
                }
            }
        }

        ConfigurationManager.RefreshSection("appSettings");

        xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }
}

}

相关问题