推进门户网站建设工作,企业营销策划推广,随机显示wordpress,保山网站建设优化读取xml文件转成ListT对象的两种方法#xff08;附源码#xff09;读取xml文件#xff0c;是项目中经常要用到的#xff0c;所以就总结一下#xff0c;最近项目中用到的读取xml文件并且转成ListT对象的方法#xff0c;加上自己知道的另一种实现方法。 就… 读取xml文件转成ListT对象的两种方法附源码 读取xml文件是项目中经常要用到的所以就总结一下最近项目中用到的读取xml文件并且转成ListT对象的方法加上自己知道的另一种实现方法。 就以一个简单的xml做例子。 xml格式如下 1 ?xml version1.0?
2 products
3 product nameWest Side Story price9.99 supplierId1 /
4 product nameAssassins price14.99 supplierId2 /
5 product nameFrogs price13.99 supplierId1 /
6 product nameSweeney Todd price10.99 supplierId3 /
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文件的内容读取出来转成ListProduct对象需求明白了那接下来就来介绍实现的方法。 一、利用.net中的XmlSerializer类提供的方法 1、首先要在Product、Products类中的每个属性上加上与xml对应的描述字段如下代码 [XmlRoot(products)]public class Products{[XmlElement(product)]public Product[] Items { get; set; }} 1 public class Product2 {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 IListProduct productsnew ListProduct();2 static LoadXml()3 {4 try5 {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 IListProduct productsnew ListProduct();2 static LoadXml()3 {4 try5 {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 } 以上就是这么多其实很简单就是记录下来做一个笔记如果各位看官有更好的实现方法可以分享一下大家互相学习学习 源码下载 转载于:https://www.cnblogs.com/junjieok/p/3470530.html