• XML序列之System.Xml.Serialization


    1,对象

    public class School
        {
            public string Name { get; set; }
            public List<Classes> listClasses { get; set; }
        }
    
        public class Classes
        {
            public string Name { get; set; }
            public int StudentNum { get; set; }
            public List<Student> listStudent { get; set; }
        }
    
        public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public int Height { get; set; }
        }

    2,序列化类

    public class XmlSerialization
        {
            #region 对象与XML字符串转换
            /// <summary>
            /// 序列化 对象转成xml字符串
            /// </summary>
            /// <param name="type"></param>
            /// <param name="obj"></param>
            /// <param name="xmlRootName"></param>
            /// <returns></returns>
            public static string Serialize(Type type, object obj, string xmlRootName)
            {
                string strXml = string.Empty;
                using (MemoryStream stream = new MemoryStream())
                {
                    type = type != null ? type : obj.GetType();
    
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    //不要命名空间
                    ns.Add(string.Empty, string.Empty);
    
                    XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
                            new System.Xml.Serialization.XmlSerializer(type) :
                            new System.Xml.Serialization.XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                    xmlSerializer.Serialize(stream, obj, ns);
    
                    stream.Position = 0;
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        strXml = sr.ReadToEnd();
                    }
                }
    
                return strXml;
            }
    
            /// <summary>
            /// 反序列化 xml字符串转成对象
            /// </summary>
            /// <param name="strXml"></param>
            /// <param name="type"></param>
            /// <returns></returns>
            public static object Deserialize(string strXml, Type type)
            {
                object obj = null;
                using (StringReader sr = new StringReader(strXml))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(type);
                    obj = xmlSerializer.Deserialize(sr);
                }
                return obj;
            }
    
            #endregion
    
            #region 对象与XML文件转换
            /// <summary>
            /// xml文件转换为对象
            /// </summary>
            /// <param name="filePath"></param>
            /// <param name="type"></param>
            /// <returns></returns>
            public static object LoadFromXml(string filePath, Type type)
            {
                object result = null;
    
                if (File.Exists(filePath))
                {
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                        XmlSerializer xmlSerializer = new XmlSerializer(type);
                        result = xmlSerializer.Deserialize(reader);
                    }
                }
    
                return result;
            }
    
            /// <summary>
            /// 对象保存为xml文件
            /// </summary>
            /// <param name="filePath"></param>
            /// <param name="sourceObj"></param>
            /// <param name="type"></param>
            /// <param name="xmlRootName"></param>
            public static void SaveToXml(string filePath, object sourceObj, Type type, string xmlRootName)
            {
                if (!string.IsNullOrEmpty(filePath) && sourceObj != null)
                {
                    type = type != null ? type : sourceObj.GetType();
    
                    using (StreamWriter writer = new StreamWriter(filePath))
                    {
                        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                        ns.Add("", "");
                        var xmlSerializer = string.IsNullOrEmpty(xmlRootName) ?
                            new XmlSerializer(type) :
                            new XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                        xmlSerializer.Serialize(writer, sourceObj, ns);
                    }
                }
            }
            #endregion
        }

    3,给对象赋值,看序列化为xml是什么样子

    private void btnSeria_Click(object sender, EventArgs e)
            {
                School modelSchool = new School();
                modelSchool.Name = "3School";
    
                modelSchool.listClasses = new List<Classes>();
                Classes mClasses = new Classes();
                mClasses.StudentNum = 20;
                mClasses.Name = "class3";
    
                mClasses.listStudent = new List<Student>();
                mClasses.listStudent.Add(new Student() { Age=12, Name="lily", Height=160 });
                mClasses.listStudent.Add(new Student() { Age = 12, Name = "lucy", Height = 165 });
                modelSchool.listClasses.Add(mClasses);
    
                mClasses = new Classes();
                mClasses.StudentNum = 21;
                mClasses.Name = "class4";
    
                mClasses.listStudent = new List<Student>();
                mClasses.listStudent.Add(new Student() { Age = 14, Name = "green", Height = 166 });
                mClasses.listStudent.Add(new Student() { Age = 14, Name = "valeey", Height = 164 });
    
                modelSchool.listClasses.Add(mClasses);
    
                //
                string x = XmlSerialization.Serialize(typeof(School), modelSchool,"");
                this.textBox1.Text = x;
            }

    结果:

    <?xml version="1.0"?>
    <School>
      <Name>3School</Name>
      <listClasses>
        <Classes>
          <Name>class3</Name>
          <StudentNum>20</StudentNum>
          <listStudent>
            <Student>
              <Name>lily</Name>
              <Age>12</Age>
              <Height>160</Height>
            </Student>
            <Student>
              <Name>lucy</Name>
              <Age>12</Age>
              <Height>165</Height>
            </Student>
          </listStudent>
        </Classes>
        <Classes>
          <Name>class4</Name>
          <StudentNum>21</StudentNum>
          <listStudent>
            <Student>
              <Name>green</Name>
              <Age>14</Age>
              <Height>166</Height>
            </Student>
            <Student>
              <Name>valeey</Name>
              <Age>14</Age>
              <Height>164</Height>
            </Student>
          </listStudent>
        </Classes>
      </listClasses>
    </School>

    4,如果想根节点School变成MySchool怎么办呢?只需要在School类上加一个标签:

    [XmlRoot("MySchool")]
        public class School
        {
            public string Name { get; set; }
            public List<Classes> listClasses { get; set; }
        }

    结果:

    <?xml version="1.0"?>
    <MySchool>
      <Name>3School</Name>
      <listClasses>
        <Classes>
          <Name>class3</Name>
          <StudentNum>20</StudentNum>
          <listStudent>
            <Student>
              <Name>lily</Name>
              <Age>12</Age>
              <Height>160</Height>
            </Student>
            <Student>
              <Name>lucy</Name>
              <Age>12</Age>
              <Height>165</Height>
            </Student>
          </listStudent>
        </Classes>
        <Classes>
          <Name>class4</Name>
          <StudentNum>21</StudentNum>
          <listStudent>
            <Student>
              <Name>green</Name>
              <Age>14</Age>
              <Height>166</Height>
            </Student>
            <Student>
              <Name>valeey</Name>
              <Age>14</Age>
              <Height>164</Height>
            </Student>
          </listStudent>
        </Classes>
      </listClasses>
    </MySchool>

    或者:

    [XmlRootAttribute("MySchool")]
        public class School
        {
            public string Name { get; set; }
            public List<Classes> listClasses { get; set; }
        }
        

    或者:

    [XmlType("MySchool")]
    public class School
    {
    public string Name { get; set; }
    public List<Classes> listClasses { get; set; }
    }

    也可以得到同样结果。

    5,如果要把School的Name作为School节点的属性,如:<School Name="3School">,该怎么做呢?只需要在Name属性上加上[XmlAttribute]标签。

    如:

    [XmlAttribute]
    public string Name { get; set; }
    public List<Classes> listClasses { get; set; }

    结果:

    <?xml version="1.0"?>
    <School Name="3School">
      <listClasses>
        <Classes>
          <Name>class3</Name>
          <StudentNum>20</StudentNum>
          <listStudent>
            <Student>
              <Name>lily</Name>
              <Age>12</Age>
              <Height>160</Height>
            </Student>
            <Student>
              <Name>lucy</Name>
              <Age>12</Age>
              <Height>165</Height>
            </Student>
          </listStudent>
        </Classes>
        <Classes>
          <Name>class4</Name>
          <StudentNum>21</StudentNum>
          <listStudent>
            <Student>
              <Name>green</Name>
              <Age>14</Age>
              <Height>166</Height>
            </Student>
            <Student>
              <Name>valeey</Name>
              <Age>14</Age>
              <Height>164</Height>
            </Student>
          </listStudent>
        </Classes>
      </listClasses>
    </School>

    6,要把List表现为水平结构的Xml节点该怎么做呢?在List属性上加上[XmlElement]特性。

    如对象为:

    public class School
        {
            [XmlAttribute]
            public string Name { get; set; }
            [XmlElement("Classes")]
            public List<Classes> listClasses { get; set; }
        }
        
        public class Classes
        {
            [XmlAttribute]
            public string Name { get; set; }
            [XmlAttribute]
            public int StudentNum { get; set; }
            [XmlElement("Student")]
            public List<Student> listStudent { get; set; }
        }
    
        public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public int Height { get; set; }
        }

    结果:

    <?xml version="1.0"?>
    <School Name="3School">
      <Classes Name="class3" StudentNum="20">
        <Student>
          <Name>lily</Name>
          <Age>12</Age>
          <Height>160</Height>
        </Student>
        <Student>
          <Name>lucy</Name>
          <Age>12</Age>
          <Height>165</Height>
        </Student>
      </Classes>
      <Classes Name="class4" StudentNum="21">
        <Student>
          <Name>green</Name>
          <Age>14</Age>
          <Height>166</Height>
        </Student>
        <Student>
          <Name>valeey</Name>
          <Age>14</Age>
          <Height>164</Height>
        </Student>
      </Classes>
    </School>

    7,Classes节点下的Student列表名称不一样。

    先在Classes类中再加一个Student的List对象。如:

    public class School
        {
            [XmlAttribute]
            public string Name { get; set; }
            [XmlElement("Classes")]
            public List<Classes> listClasses { get; set; }
        }
        
        public class Classes
        {
            [XmlAttribute]
            public string Name { get; set; }
            [XmlAttribute]
            public int StudentNum { get; set; }
            [XmlElement("Student")]
            public List<Student> listStudent { get; set; }
            [XmlElement("GoodStudent")]
            public List<Student> listGoodStudent { get; set; }
        }
    
        public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public int Height { get; set; }
        }

    结果:

    <?xml version="1.0"?>
    <School Name="3School">
      <Classes Name="class3" StudentNum="20">
        <Student>
          <Name>lily</Name>
          <Age>12</Age>
          <Height>160</Height>
        </Student>
        <Student>
          <Name>lucy</Name>
          <Age>12</Age>
          <Height>165</Height>
        </Student>
      </Classes>
      <Classes Name="class4" StudentNum="21">
        <Student>
          <Name>green</Name>
          <Age>14</Age>
          <Height>166</Height>
        </Student>
        <Student>
          <Name>valeey</Name>
          <Age>14</Age>
          <Height>164</Height>
        </Student>
        <GoodStudent>
          <Name>green1</Name>
          <Age>14</Age>
          <Height>159</Height>
        </GoodStudent>
        <GoodStudent>
          <Name>valeey1</Name>
          <Age>14</Age>
          <Height>163</Height>
        </GoodStudent>
      </Classes>
    </School>

    XML序列化时的一些重要特性:

    [XmlRootAttribute("MySchool")]     // 当该类为Xml根节点时,以此为根节点名称。
    public class School
    
    [XmlAttribute("AreaName")]    // 表现为Xml节点属性。<... AreaName="..."/>
    public string Name
    
    [XmlElementAttribute("Num", IsNullable = false)]    // 表现为Xml节点。<Num>...</Num>
    public int StudentNum
    
    [XmlArrayAttribute("Students")]    // 表现为Xml层次结构,根为Areas,其所属的每个该集合节点元素名为类名。<Students><Student ... /><Student ... /></Students>
    List<Student> listStudent
    [XmlArrayAttribute("Students")] 
    Student[] Students
    [XmlElementAttribute("Area", IsNullable = false)]    // 表现为水平结构的Xml节点。<Student ... /><Student ... />...
    List<Student> listStudent
    XmlElementAttribute("Area", IsNullable = false)]
    Student[] Students
    [XmlIgnoreAttribute]    // 忽略该元素的序列化。

    demo:https://files.cnblogs.com/files/crazy29/XML%E5%BA%8F%E5%88%97%E5%8C%96.rar

  • 相关阅读:
    穷举 迭代 while
    for 循环
    switch case
    if else 语句
    数据类型
    语句的输入、输出
    控件——DataGridview
    mysql-bin.000001文件的来源及处理方法
    /var/log目录下的20个Linux日志文件功能详解
    CountDownLatch
  • 原文地址:https://www.cnblogs.com/crazy29/p/6384432.html
Copyright © 2020-2023  润新知