C#实现对象序列化为XML

C#实现对象序列化为XML
原创weixin_38660590 发布于2019-03-02 13:42:24 阅读数 629  收藏
展开
对象序列化有两种方式

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>
————————————————
版权声明:本文为CSDN博主「weixin_38660590」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38660590/article/details/88075011

posted @ 2020-01-02 09:12  grj001  阅读(327)  评论(0编辑  收藏  举报