zoukankan      html  css  js  c++  java
  • 反序列化xml

    我是.net 菜鸟。

    今天学习一下反序列化xml,即将xml文件转换成程序更好识别的对象。

    下面来看一个例子。这是一个xml文件。

    <xml>

    <students>

    <student>

    <fields>

    <field value="name"><field>

    <field value="id"></field>

    </fields>

    <contact value="phoneNumber">

    <telephone type="number">urgent="number">urgent contactor's number</telephone>

    <telephone type="number">urgent="number">>apartment number</telephone>

    </contact>

    </student>

    </students>

    </xml>

     好了,这是一个比较简单的xml文件。

    现在开始写反序列化的操作。

    在你的实现类中写一个方法

    public class ChangeXml{

    public static T DeserializeObject<T>(string xml)
            {
                var str= new StringReader(xml);
                var xmlSerializer= new XmlSerializer(typeof(T));
                var result= (T)xmlSerializer.Deserialize(str);
                return result;
            }

    }

    [XmlType(TypeName = "xml")]
        public class XmlElement
        {
            [XmlArray("Students", IsNullable = false)]
            [XmlArrayItem("Student", IsNullable = false)]
            public List<StudentElement> Students{ get; set; }
        }

     public class StudentElement
        {
           
            [XmlArray("fields", IsNullable = false)]
            [XmlArrayItem("field", IsNullable = false)]
            public List<FieldElement> fields{ get; set; }

            [XmlArray("contact", IsNullable = false)]
            [XMLAttribute("value")
            public string value{get;set;}
            [XmlArrayItem("telephone", IsNullable = false)]
            public List<PhoneElement> contact{ get; set; } 

    }

     public class PhoneElement
    {
            [XmlAttribute("type")]
            public string type{ get; set; }

            [XmlText]
            public string Value { get; set; }

      }

      

    最后调用DeserializeObject<XmlElement>()方法就行了

  • 相关阅读:
    专业词汇-数学-运算:四则运算
    专业词汇-数学-运算:逆运算
    专业词汇-数学:运算
    DNF Package Management-CentOS 8
    Change the HostName of CentOS 8
    CentOS8 修改SSH端口,禁用root登录,修改SSH协议
    CentOS8 Disable IPV6 and Selinux
    Ubuntu 20.04 Install SSH, Change SSH Port, Enable root
    ubuntu 20.04 重启网卡服务
    Ubuntu 20.04 Install Guest Additions for VirtualBox
  • 原文地址:https://www.cnblogs.com/qiny/p/2995794.html
Copyright © 2011-2022 走看看