讀取xml文件轉成List 對象的兩種方法(附源碼)


讀取xml文件轉成List<T>對象的兩種方法(附源碼)

  讀取xml文件,是項目中經常要用到的,所以就總結一下,最近項目中用到的讀取xml文件並且轉成List<T>對象的方法,加上自己知道的另一種實現方法。

  就以一個簡單的xml做例子。

xml格式如下:

1 <?xml version="1.0"?>
2 <products>
3   <product name="West Side Story" price="9.99" supplierId="1" />
4   <product name="Assassins" price="14.99" supplierId="2" />
5   <product name="Frogs" price="13.99" supplierId="1" />
6   <product name="Sweeney Todd" price="10.99" supplierId="3" />
7 </products>

Product對象如下:

1     public class Product
2     {
3         public string Name { get; set; }
4 
5         public decimal Price { get; set; }
6 
7         public decimal SupplierId { get; set; }
8     }

要實現的就是要把xml文件的內容讀取出來轉成List<Product>對象,需求明白了,那接下來就來介紹實現的方法。

 

一、利用.net中的XmlSerializer類提供的方法

1、首先要在Product、Products類中的每個屬性上加上與xml對應的描述字段,如下代碼:

    [XmlRoot("products")]
    public class Products
    {
        [XmlElement("product")]
        public Product[] Items { get; set; }
    }

 

 1     public class Product
 2     {
 3         [XmlAttribute(AttributeName = "name")]
 4         public string Name { get; set; }
 5 
 6         [XmlAttribute(AttributeName = "price")]
 7         public decimal Price { get; set; }
 8 
 9         [XmlAttribute(AttributeName = "supplierId")]
10         public decimal SupplierId { get; set; }
11     }

注意AttributeName一定要和xml中的一致。

2、相應的對應關系建立好了之后,下面就來進行讀取反序列化,代碼如下:

 1         private static IList<Product> products=new List<Product>();
 2         static LoadXml()
 3         {
 4             try
 5             {
 6                 using (TextReader reader = new StreamReader("data.xml"))
 7                 {
 8                     var serializer = new XmlSerializer(typeof(Products));
 9                     var items = (Products)serializer.Deserialize(reader);
10                     if (items != null)
11                     {
12                         products = items.Items;
13                     }
14                 }
15             }
16             catch (Exception ex)
17             {
18                 Console.WriteLine("出錯了," + ex.Message);
19             }
20         }

這個方法里也沒什么特別的就是先讀取.xml內容,然后再反Deserialize方法反序化xml內容轉成Products。

這種方法大致就這么簡單,我個人是比較傾向於這種方法的,因為它不用自己去解析xml中相應的屬性等內容,也比較靈活,xml中的屬性名變了,在類中相應的屬性上改一下AttributeName的值就可以了。

 

二、利用linq進行轉換

這個會linq的估計都知道吧,具體不多說了,代碼如下:

 1         private static IList<Product> products=new List<Product>();
 2         static LoadXml()
 3         {
 4             try
 5             {
 6                 XDocument doc = XDocument.Load("data.xml");
 7                 products =
 8                     doc.Descendants("product")
 9                        .Select(
10                            x =>
11                            new Product
12                                {
13                                    Name = x.Attribute("name").ToString(),
14                                    Price = (decimal)x.Attribute("price"),
15                                    SupplierId = (long)x.Attribute("supplierId")
16                                })
17                        .ToList();
18             }
19             catch (Exception ex)
20             {
21                 Console.WriteLine("出錯了," + ex.Message);
22             }
23         }

以上就是這么多,其實很簡單,就是記錄下來,做一個筆記,如果各位看官有更好的實現方法,可以分享一下,大家互相學習學習!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM