1、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>
<orders>
<order>
<id>10643</id>
<orderdate>1997-08-25T00:00:00</orderdate>
<total>814.50</total>
</order>
<order>
<id>10692</id>
<orderdate>1997-10-03T00:00:00</orderdate>
<total>878.00</total>
</order>
<order>
<id>10702</id>
<orderdate>1997-10-13T00:00:00</orderdate>
<total>330.00</total>
</order>
<order>
<id>10835</id>
<orderdate>1998-01-15T00:00:00</orderdate>
<total>845.80</total>
</order>
<order>
<id>10952</id>
<orderdate>1998-03-16T00:00:00</orderdate>
<total>471.20</total>
</order>
<order>
<id>11011</id>
<orderdate>1998-04-09T00:00:00</orderdate>
<total>933.50</total>
</order>
</orders>
</customer>
</customers>
2、Customer类:
public class Customer
{
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 Order[] Orders { get; set; }
}
3、读取数据
List<Customer> lists = (from customer in XDocument.Load("Customers.xml").Root.Elements("customer")
select new Customer
{
CustomerID = (string)customer.Element("id"),
CompanyName = (string)customer.Element("name"),
Address = (string)customer.Element("address"),
City = (string)customer.Element("city"),
Region = (string)customer.Element("region"),
PostalCode = (string)customer.Element("postalcode"),
Country = (string)customer.Element("country"),
Phone = (string)customer.Element("phone"),
Fax = (string)customer.Element("fax"),
Orders = (from order in customer.Elements("orders").Elements("order")
select new Order
{
OrderID = (int)order.Element("id"),
OrderDate = (DateTime)order.Element("orderdate"),
Total = (decimal)order.Element("total")
}).ToArray()
}).ToList();