C#XML查询显示异常错误

时间:2016-11-02 02:59:02

标签: c# xml

我尝试根据用户提交的xml文档和用户提交的XPath语法在富文本框中显示一些XML结果。我的问题是我一直收到错误:

  An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe
  Additional information: Object reference not set to an instance of an object.

以下是我的代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "XML |*.xml";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(ofd.FileName); 
            richTextBox1.Text = xDoc.SelectSingleNode(textBox1.Text).InnerText;
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

更改此行

richTextBox1.Text = xDoc.SelectSingleNode(textBox1.Text).InnerText;

XmlNode node = xDoc.SelectSingleNode(textBox1.Text);
if(node != null)
   richTextBox1.Text = node.InnerText;

调查节点为空的原因。