【问题标题】:C# XmlElement: Why does it always return Nulll?C# XmlElement:为什么总是返回 Null?
【发布时间】:2017-03-14 23:31:09
【问题描述】:

我对 C# 比较陌生,刚开始使用 XmlElement 和 SingleNode 方法。出于某种原因,“customSettings”一直返回 null,尽管 XML 文档已正确加载。我已经通过将其加载为字符串来检查它。到目前为止,我已经尝试了所有我能想象到的东西,包括评论中的尝试。非常感谢任何帮助或建议。这是我的 XML 文档:

编辑:使用 CodingYoshi 的解决方案,但有更好的方法吗?

编辑:更改了 NSGaga 的 XML 和代码,以使用 user.config 中的 NameValueCollection 解决只读异常

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="users_fächer" type="System.Configuration.NameValueSectionHandler" />
  </configSections>
  <users_faecher>
    <add key="user1" value="value1" />
    <add key="user2" value="value2" />
  </users_faecher>
</configuration>

代码:

string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Users.config");
string new_fächer = input[1];
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = dir;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

ConfigurationSection myParamsSection = config.GetSection("users_faecher");

string myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml();
XmlDocument sectionXmlDoc = new XmlDocument();
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml));
NameValueSectionHandler handler = new NameValueSectionHandler();

NameValueCollection users_fächer = handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection;

users_fächer.Set(user, new_fächer);
config.Save(ConfigurationSaveMode.Modified, true);

【问题讨论】:

  • Nikolas 能否发布一个小型控制台项目 - var customSettings = ConfigurationManager.GetSection("data/faecher") as NameValueCollection; 不应该返回 null,那里的一切都是正确的。而且您不应该将配置文件作为 XML 加载,因为这很蹩脚:)。这里还有其他问题,我只是不确定你在做什么。所以去掉所有其他的东西,就像你拥有它和那一行一样
  • @NSGaga 在打开该部分时发现了问题,但是当我在 NameValueCollection 上尝试设置方法时,它告诉我它是只读的,尽管它是自定义的 user.config 而不是 app.config。我编辑了代码和 xml 数据,让你看看我现在得到了什么
  • @NSGaga 现在全部编辑了,你知道为什么它不让我编辑吗?

标签: c# xml config selectnodes


【解决方案1】:

这将为您提供第一个 add 元素:

doc.ChildNodes[0].NextSibling.ChildNodes[1].ChildNodes[0].ChildNodes[0];

这将为您获取第一个 add 元素的 value 属性。

doc.ChildNodes[0].NextSibling.ChildNodes[1]
    .ChildNodes[0].ChildNodes[0].Attributes["value"].Value;

【讨论】:

  • 虽然现在正在工作,这太棒了,你知道如何修复以前的或修改你的,以便不必遍历所有孩子来找到具有正确关键属性的孩子吗?
  • 你为什么关心循环查找你需要的目标元素?如果您担心性能:您多久会这样做一次?这会成为瓶颈吗?
猜你喜欢
  • 2014-09-12
  • 2019-09-18
  • 2014-09-02
  • 2015-02-27
  • 2021-01-10
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多