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);
}
}