基本上你的意思是:将对象转换为 XML 并将 XML 转换为对象。这可以通过
using System.Xml.Serialization;
假设您有一个列表:
public List<Product> GetProductList()
{
List<Product> list = new List<Product>();
Product product = new Product(new Section[3]);
product.Sections[0] = new Section("1", new Header[3]);
product.Sections[0].Headers[0] = new Header("P1", "C1", "T1");
product.Sections[0].Headers[1] = new Header("P2", "C2", "T2");
product.Sections[1] = new Section("2", new Header[3]);
product.Sections[1].Headers[0] = new Header("P1", "C1", "T1");
product.Sections[1].Headers[1] = new Header("P2", "C2", "T2");
list.Add(product);
return list;
}
您可以将其序列化为:
private void Serialize()
{
List<Product> list = GetProductList();
XmlSerializer serializer = new XmlSerializer(typeof(List<Product>));
TextWriter tw = new StreamWriter(Server.MapPath("book1.xml"));
serializer.Serialize(tw, list);
tw.Close();
}
和反序列化一样:
public void DeSerialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Product>));
TextReader tr = new StreamReader(Server.MapPath("book1.xml"));
List<Product> b = (List<Product>)serializer.Deserialize(tr);
tr.Close();
Foreach (Product product in b)
{
Response.Write(product.Sections[0].Name + ",");
Response.Write(product.Sections[1].Name);
}
}