linq读取xml

前端之家收集整理的这篇文章主要介绍了linq读取xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
var customerList = (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"),Orders = (
                                        from o in e.Elements("orders").Elements("order")
                                        select new Order
                                        {
                                            OrderID = (int)o.Element("id"),OrderDate = (DateTime)o.Element("orderdate"),Total = (decimal)o.Element("total")
                                        }).ToArray()
                                }).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>
    <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>
....

猜你在找的XML相关文章