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

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

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

  1. public class ChangeLanguage
  2. {
  3. public void UpdateConfig(string key, string value)
  4. {
  5. var xmlDoc = new XmlDocument();
  6. xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
  7. foreach (XmlElement xmlElement in xmlDoc.DocumentElement)
  8. {
  9. if (xmlElement.Name.Equals("appSettings"))
  10. {
  11. foreach (XmlNode xNode in xmlElement.ChildNodes)
  12. {
  13. if (xNode.Attributes[0].Value.Equals(key))
  14. {
  15. xNode.Attributes[1].Value = value;
  16. }
  17. }
  18. }
  19. }
  20. ConfigurationManager.RefreshSection("appSettings");
  21. xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
  22. }
  23. }
  24. }
xdnvmnnf

xdnvmnnf1#

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

  1. public class ChangeLanguage
  2. {
  3. public void UpdateConfig(string key, string value)
  4. {
  5. var xmlDoc = new XmlDocument();
  6. xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
  7. foreach (var xmlElement in xmlDoc.DocumentElement.OfType<XmlElement>())
  8. {
  9. if (xmlElement.Name.Equals("appSettings"))
  10. {
  11. foreach (XmlNode xNode in xmlElement.ChildNodes)
  12. {
  13. if (xNode.Attributes[0].Value.Equals(key))
  14. {
  15. xNode.Attributes[1].Value = value;
  16. }
  17. }
  18. }
  19. }
  20. ConfigurationManager.RefreshSection("appSettings");
  21. xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
  22. }
  23. }

}

展开查看全部

相关问题