读取空值并从 XML 文件 C# 获胜返回空值

本文关键字:空值 获胜 返回 文件 XML 读取 | 更新日期: 2023-09-27 18:34:08

<?xml version="1.0" encoding="utf-8"?>
<configuration version="45.2012.4.23" xmlns="http://www.example.com/">
  <description>example.com</description>
  <reading />
  <connection>
    <sourceId>452342341</sourceId>  
    <organization/>
    <field>*</field>
  </connection>
  <source>
    <sourceId>452342341</sourceId>
    <connectionContext>
      <id />
      <name>testing</name>
      <description />
      <contextType>Section</contextType>      
      <organization/>
      <field>Demo Field</field>
      <section>testing</section>
      <subSection />
    </connectionContext>
    <Mode>Section</Mode>
    <activity>bell Testing</activity>
  </source>
</configuration>

我想读取此 xml 并以窗口窗体textboxes显示数据。

当我在列表框中选择 xml 文件时,我想从connection标签中读取第一组数据,从connectionContext标签中读取第二组数据,在文本框中显示值。

当存在空值时,以下代码不起作用的问题???

 private void DisplayFile(string path)
        {
            var doc = XDocument.Load(path);
            var ns = doc.Root.GetDefaultNamespace();
            var conn = doc.Root.Element(ns + "connection");
            textBox1.Text = conn.Element(ns + "sourceId").Value;
            textBox3.Text = conn.Element(ns + "description").Value;
            textBox4.Text = conn.Element(ns + "uri").Value;
            textBox5.Text = conn.Element(ns + "username").Value;
            var conn1 = doc.Root.Element(ns + "connectionContext");
            textBox7.Text = conn1.Element(ns + "field").Value;
            textBox8.Text = conn1.Element(ns + "bellName").Value;
            textBox9.Text = conn1.Element(ns + "id").Value;
            textBox10.Text = conn1.Element(ns + "bellboreName").Value;    
        }

此字段Object reference not set to an instance of an object. Object reference not set to an instance of an object.错误消息(ns + "field").Value;

读取空值并从 XML 文件 C# 获胜返回空值

>connectionContext位于文档根目录下source而不是文档根目录下,因此您需要更改以下内容:

var conn1 = doc.Root.Element(ns + "connectionContext");

对此:

var conn1 = doc.Root.Element(ns + "source").Element(ns + "connectionContext");

或者,在架构中允许更大的灵活性:

var conn1 = doc.Descendants(ns + "connectionContext").First();