zoukankan      html  css  js  c++  java
  • C# xml序列化与反序列化 特性的使用

     示例,主要包括System.Xml.Serialization命名空间下的XmlRoot、XmlElement、XmlAttribute、XmlText、XmlIgnore等特性的简单使用,高级使用可自行查看msdn。

    实体类代码:

        [XmlRoot("信息")]  // 该特性标记为根节点
        public class Info
        {
            [XmlIgnore]  // 此公共属性不会被序列化
            public int Count { get; set; }
    
            public Server 服务端 { get; set; }  // 不使用标记
    
            [XmlElement("客户端")]  // List<Client> 表示有多个 '客户端' 节点
            public List<Client> Client { get; set; }
        }
    
        public class Server
        {
            [XmlAttribute("备注")]  // 节点 '服务端' 的一个名为 '备注' 的属性
            public string Note;
    
            [XmlText]  // 节点 '服务端' 的值
            public string Name;
        }
    
        public class Client
        {
            [XmlAttribute("名称")]  // 在 '客户端' 节点添加名为 '名称' 的属性
            public string Name { get; set; }
    
            [XmlElement("地址")]  // 节点 '客户端' 的子节点
            public string Adress { get; set; }
    
            [XmlElement("端口")]  // 节点 '客户端' 的子节点
            public string Port { get; set; }
    
        }
    View Code

    实例化代码:

                Info info = new Info
                {
                    Count = 2,
                    服务端 = new Server
                    {
                        Name = "用户服务",
                        Note = "无实际意义"
                    },
                    Client = new List<Client>
                    {
                        new Client
                        {
                            Name = "测试用户",
                            Adress = "192.168.1.0",
                            Port = "6666"
                        },
                        new Client
                        {
                            Name = "",
                            Adress = "192.168.1.1",
                            Port = "7777"
                        }
                    }
                };
    View Code

    序列化结果:

    <?xml version="1.0"?>
    <信息>
      <服务端 备注="无实际意义">用户服务</服务端>
      <客户端 名称="测试用户">
        <地址>192.168.1.0</地址>
        <端口>6666</端口>
      </客户端>
      <客户端 名称="">
        <地址>192.168.1.1</地址>
        <端口>7777</端口>
      </客户端>
    </信息>

    值得一提的是,在实际运用中,自定义命名空间[xmlns:......]的方法是使用XmlSerializer类的重载方法:

    public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces);

    进行序列化,其中“namespaces”参数可由以下代码创建:

    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(
    new[] { new XmlQualifiedName(string.Empty, "") });

  • 相关阅读:
    [轉]Flex实现代码分离mxml/as
    [轉]PHP执行MYSQL存储过程报错:Commands out of sync; you can't run this command now 问题的解决
    [轉]mysqli & pdo使用实例和详解
    JSON格式驗證以及格式說明
    [轉]can't return a result set in the given context及参数解释
    PHP ADODB資源
    [轉]Virtual PC 网络设置(Networking)
    [轉]20个非常有用的PHP类库
    [轉]MySQL存储过程 ERROR Handler 异常处理
    [轉]如何通过Jquery获取radio的值
  • 原文地址:https://www.cnblogs.com/xuanhu/p/9393534.html
Copyright © 2011-2022 走看看