读取空值并从xml文件C#winforms返回null

时间:2012-05-14 07:32:55

标签: c# xml visual-studio-2010 linq

<?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并在Windows窗体的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;

1 个答案:

答案 0 :(得分:2)

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();