通过XmlSerializer序列化(对象)和反序列化(xml文件)

xml文件

<?xml version="1.0"?>
<User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>issac</Name>
<Age>25</Age>
<Address>
<Adrs>123</Adrs>
</Address>
</User>

[XmlRoot("User")]
    public class User
    {
        [XmlElement("Name")]
        public string Name { get; set; }

        [XmlElement("Age")]
        public int Age { get; set; }

        [XmlElement("Address")]
        public Address Address1 { get; set; }
    }
    public class Address
    {
        [XmlElement("Adrs")]
        public string [] Adrs1 { get; set; }
    }

具体操作

string path = HttpContext.Current.Server.MapPath("~/Config/User.config");
        //反序列化加载xml文件到对象
        protected void Page_Load(object sender, EventArgs e)
        {
            XmlSerializer xs = new XmlSerializer(typeof(User));
            FileStream fs = new FileStream(path, FileMode.Open);
            User user = (User)xs.Deserialize(fs);
            Response.Write(user.Address1.Adrs1[0]);
            fs.Close();
        }
        //序列化对象到xml(修改xml)
        protected void btnUpdata_Click(object sender, EventArgs e)
        {
            User user = new User() { Name = "issac", Age = 25};
            FileStream fs = new FileStream(path, FileMode.Open);
            XmlSerializer xs = new XmlSerializer(typeof(User));
            xs.Serialize(fs, user);
            fs.Close();
        }
posted @ 2011-03-15 16:14  凌鸢  阅读(727)  评论(0编辑  收藏  举报