加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

读取xml文件转成List<T>对象的两种方法

发布时间:2020-12-15 23:12:14 所属栏目:百科 来源:网络整理
导读:xml格式如下: ?xml version="1.0"? products product name="West Side Story" price="9.99" supplierId="1" / product name="Assassins" price="14.99" supplierId="2" / product name="Frogs" price="13.99" supplierId="1" / product name="Sweeney Todd"

xml格式如下:

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


product 对象如下:

public class Product
{
public string Name { get; set; }

public decimal Price { get; set; }

public decimal SupplierId { get; set; }
}


利用.net中的XmlSerializer将xml转换成对象


1、首先要在Product、Products类中的每个属性上加上与xml对应的描述字段,如下代码:

    [XmlRoot("products")]
    public class Products
    {
        [XmlElement("product")]
        public Product[] Items { get; set; }
    }
     public class Product
      {
          [XmlAttribute(AttributeName = "name")]
          public string Name { get; set; }
  
          [XmlAttribute(AttributeName = "price")]
          public decimal Price { get; set; }
  
          [XmlAttribute(AttributeName = "supplierId")]
         public decimal SupplierId { get; set; }
     }

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

2、相应的对应关系建立好了之后,下面就来进行读取反序列化,代码如下:

private static IList<Product> products=new List<Product>(); static LoadXml() { try { using (TextReader reader = new StreamReader("data.xml")) { var serializer = new XmlSerializer(typeof(Products)); var items = (Products)serializer.Deserialize(reader); if (items != null) { products = items.Items; } } } catch (Exception ex) { Console.WriteLine("出错了," + ex.Message); } }

转自http://www.cnblogs.com/junjieok/archive/2013/12/12/3470530.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读