2013-05-01 43 views
0

我有一个XML文件名称Customerx.xml。它的父标签为。它有很多。为什么在尝试从XML文件中读取数据时会得到Null Referenfe异常?

我的客户类的定义为:在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 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()方法在阅读我得到一个空引用execption来自xlm文件的数据?这是为什么发生?我怎样才能摆脱它?

+2

哪条线?你的XML是什么样的?一个简短的*完整的*程序展示这个问题真的会有帮助... – 2013-05-01 15:12:14

+0

几乎所有'NullReferenceException'的情况都是一样的。请参阅“[什么是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)”的一些提示。 – 2013-05-01 15:19:57

+0

@JonSkeet,我编辑了我的问题。现在我也提供了两个xml数据。我得到错误var list = from ...这行在CreateCustomerLists()mehod上。 – Pankouri 2013-05-01 15:20:56

回答

1

要回答您的其他问题:如果您从Visual Studio中的Debug运行,那么debug文件夹将成为它用于查找文件的相对路径的开始。你需要包含的任何文件都应该放在那里。

相关问题