首先建立一个winform项目,再在上面拖一个webBrowser控件,和一个button按钮
解析product类
首先要先将类名和字段上添加XmlRootAttribute和字段属性上添加XmlElementAttribute以标示期可以被解析
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace formSerial
{
[XmlRootAttribute]
public class Product
{
private int prodId;
[XmlElementAttribute]
publicint ProductId
{
get { return prodId; }
set { prodId = value; }
}
private string prodName;
[XmlElementAttribute]
public string ProductName
{
get { return prodName; }
set { prodName = value; }
}
private int suppId;
[XmlElementAttribute]
publicint SupplierID
{
get { return suppId; }
set { suppId = value; }
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace formSerial
{
[XmlRootAttribute]
public class Product
{
private int prodId;
[XmlElementAttribute]
publicint ProductId
{
get { return prodId; }
set { prodId = value; }
}
private string prodName;
[XmlElementAttribute]
public string ProductName
{
get { return prodName; }
set { prodName = value; }
}
private int suppId;
[XmlElementAttribute]
publicint SupplierID
{
get { return suppId; }
set { suppId = value; }
}
}
}
button事件如下
View Code
private void button1_Click(object sender, EventArgs e)
{
Product pd = new Product();
pd.ProductId =12;
pd.ProductName = "C#高级编程";
pd.SupplierID =300;
TextWriter tr = new StreamWriter("sa.xml");
//定义序列化对象
XmlSerializer sr = new XmlSerializer(typeof(Product));
sr.Serialize(tr, pd);
tr.Close();
webBrowser1.Navigate(AppDomain.CurrentDomain.BaseDirectory + "sa.xml");
}
{
Product pd = new Product();
pd.ProductId =12;
pd.ProductName = "C#高级编程";
pd.SupplierID =300;
TextWriter tr = new StreamWriter("sa.xml");
//定义序列化对象
XmlSerializer sr = new XmlSerializer(typeof(Product));
sr.Serialize(tr, pd);
tr.Close();
webBrowser1.Navigate(AppDomain.CurrentDomain.BaseDirectory + "sa.xml");
}