文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>通过XmlSerializer序列化(对象)和反序列化(xml文件)

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

时间:2011-03-15  来源:凌鸢

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();
        }
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载