为什么我在尝试从XML文件中读取数据时会出现Null Reference异常?

时间:2013-05-01 15:11:01

标签: c# xml linq nullreferenceexception

我有一个XML文件名称Customerx.xml。它的父标签为。它有很多。

我的客户类定义为:

public class Customer
{
  private List<Customer> customerList;

  public string CustomerID { get; set; }
  public string CompanyName { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string Region { get; set; }
  public string PostalCode { get; set; }
  public string Country { get; set; }
  public string Phone { get; set; }
  public string Fax { get; set; }

  public List<Customer> GetCustomerList()
  {
     if (customerList == null)
        CreateCustomerLists();

     return customerList;
  }

  private void CreateCustomerLists()
  {
     var list = from e in XDocument.Load("Customers.xml").Root.Elements("customer")
                 select new Customer
                            {
                                CustomerID = (string) e.Element("id"),
                                CompanyName = (string) e.Element("name"),
                                Address = (string) e.Element("address"),
                                City = (string) e.Element("city"),
                                Region = (string) e.Element("region"),
                                PostalCode = (string) e.Element("postalcode"),
                                Country = (string) e.Element("country"),
                                Phone = (string) e.Element("phone"),
                                Fax = (string) e.Element("fax"),
                            };

      customerList = list.ToList();
  }
}

XML中的数据是:

<?xml version="1.0"?>
<customers>
  <customer>
    <id>ALFKI</id>
    <name>Alfreds Futterkiste</name>
    <address>Obere Str. 57</address>
    <city>Berlin</city>
    <postalcode>12209</postalcode>
    <country>Germany</country>
    <phone>030-0074321</phone>
    <fax>030-0076545</fax>
  </customer>
  <customer>
    <id>ANATR</id>
    <name>Ana Trujillo Emparedados y helados</name>
    <address>Avda. de la Constitución 2222</address>
    <city>México D.F.</city>
    <postalcode>05021</postalcode>
    <country>Mexico</country>
    <phone>(5) 555-4729</phone>
    <fax>(5) 555-3745</fax>
  </customer>

CreateCustomerLists()方法中,从xlm文件读取数据时,我得到一个空引用execption?为什么会这样?我怎么能摆脱它?

1 个答案:

答案 0 :(得分:1)

回答您的另一个问题:如果您从Visual Studio中的Debug运行,那么调试文件夹将是它用于查找文件的相对路径的开头。您需要包含的任何文件都应放在那里。