创建 XmlDocument 的实例时,为什么我不能多次使用 SelectSingleNode("String").InnerText?

When creating an instance of XmlDocument, why can't I use the SelectSingleNode("String").InnerText more than once?

对编码还很陌生,不确定我哪里出错了。应用程序构建但在运行时崩溃并出现错误:"Object reference not set to an instance of an object."

如果我注释掉 test2 变量和第二个条件,那么应用程序会执行我想要的操作。当我取消对上述内容的评论时,我得到一个例外。

我最终需要为 30 个复选框构建类似的东西。

如有任何帮助,我们将不胜感激。

XmlDocument xDoc = new XmlDocument();

xDoc.Load(@"\LEWBWPDEV\ComplianceXmlStorage\test.xml");
        string test1 = xDoc.SelectSingleNode("Introduction/Topic1").InnerText;
        string test2 = xDoc.SelectSingleNode("Introduction/Topic2").InnerText;

        if (test1 == "Yes")
        {
            checkBox1.CheckState = CheckState.Checked;
        }
        if (test2 == "Yes")
        {
            checkBox2.CheckState = CheckState.Checked;
        }

这意味着您的xml中没有Topic2。所以 xDoc.SelectSingleNode("Introduction/Topic2") returns null。当您尝试获取 nullInnerText 时,您会遇到异常。

解决方案 - 在获取 InnerText 之前检查是否为 null。

  var topic2 = xDoc.SelectSingleNode("Introduction/Topic2");
  if (topic2 != null && topic2.InnerText == "Yes")
      checkBox2.CheckState = CheckState.Checked;

或者您可以使用 Null-conditional operator

  string test2 = xDoc.SelectSingleNode("Introduction/Topic2")?.InnerText;

注意:我建议您使用 Linq to XML 来解析 xml

var xdoc = XDocument.Load(fileName);
string test1 = (string)xdoc.XPathSelectElement("Introduction/Topic1");
string test2 = (string)xdoc.Root.Element("Topic2");

您可以将元素转换为某些数据类型(如字符串或整数),如果元素缺失(如果数据类型接受空值),它不会抛出异常。另外如果你需要处理30个节点,你可以轻松获取它们的所有值:

var topics = from t in xdoc.Root.Elements()
             let name = t.Name.LocalName
             where name.StartsWith("Topic")
             select new {
                 Name = name,
                 IsEnabled = (string)t == "Yes"
             };

此查询将 return 从您的 xml 中收集所有主题值,您可以使用这些值来设置复选框的状态

[
  { Name: "Topic1", IsEnabled: false },
  { Name: "Topic2", IsEnabled: true }
]