0

我有一个名为 Customerx.xml 的 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 文件读取数据时,我得到一个空引用执行的方法?为什么会这样?我怎样才能摆脱它?

4

1 回答 1

1

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

于 2013-05-01T16:01:26.857 回答