对象引用未设置为对象xdocument的实例

时间:2012-04-24 10:12:27

标签: c# xml

您好我在以下代码object reference not set to an instance of an object中注明的行中收到错误有没有办法解决它?

    private void button20_Click(object sender, EventArgs e)
    {
        string blabla1 = string.Format("http://localhost:8000/Service/AuthenticateUser/{0}/{1}", textBox30.Text, textBox31.Text);
        XDocument xDoc = XDocument.Load(blabla1);
        xDoc.Element("StudentID").Value.ToList(); // object reference not set to an instance of an object?


        dataGridView12.DataSource = xDoc;
    }

1 个答案:

答案 0 :(得分:2)

如果找不到xDoc.Element("StudentID"),则调用.Value会给出该异常。

你可能想要

 //xDoc.Element("StudentID").Value.ToList();
 //List<string> ids = xDoc.Descendants("StudentID").Value.ToList();
 List<string> ids = xDoc.Descendants("StudentID").Select(e => e.Value).ToList();

但是假设XML不使用命名空间。

编辑:

  

我试图返回result.StudentID;

string id = xDoc.Descendants("StudentID").Single().Value;
相关问题