C#实现对象序列化为XML

对象序列化有两种方式

1.在需要序列化的对象类上添加特效

2.不加特性的序列化

现在实现的是第一种方式序列化对象,首先创建一个学生类(即需要序列化的对象类)

 

namespace ConsoleApplication16
{
    [XmlRoot]//表示xml的根节点
    public class Student
    {

        //需要序列化为xml的特性
        [XmlAttribute(AttributeName = "Name")]
        public string Name;

 

        [XmlAttribute(AttributeName = "Id")]
        public int Id;

       //需要序列化为xml的元素

        [XmlElement]
        public String Address;

       //SAge序列化后元素名称

        [XmlElement(ElementName = "SAge")]
        public int Age;
    }
}

//序列化过程

private static void SeriaLizeStudent(string path)
        {
            try
            {
                //创建需要序列化的对象
                Student stu = new Student
                {
                    Id = 10,
                    Name = "德玛西亚",
                    Address = "来自火星",
                    Age = 109
                };
                //创建流 path表示存储xml的文件路径
                FileStream fStream = File.OpenWrite(path);
                using (TextWriter tWriter = new StreamWriter(fStream))
                {
                    XmlSerializer xmlS = new XmlSerializer(typeof(Student));
                    xmlS.Serialize(tWriter, stu);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

//序列化后的结果

<?xml version="1.0" encoding="utf-8"?>
<Student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="德玛西亚" Id="10">
  <Address>来自火星</Address>
  <SAge>109</SAge>
</Student>

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值