0
<?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以 windows 形式显示数据。

当我在列表框中选择 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;

4

1 回答 1

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();
于 2012-05-14T08:14:21.440 回答