zoukankan      html  css  js  c++  java
  • .NET 序列化成XML, 并且格式化

    现有Person类:

        [Serializable]
        public class Person
        {
            public string Name;
            public string Info;
    
            public Person(string name)
            {
                Name = name;
            }
    
            [OnSerializing]
            public void BeforeSerialize(StreamingContext context)
            {
                Info = "Welcome, " + Name;
            }
        }

    直接用DataContractSerializer 序列化到文件后, 结果如:

    <?xml version="1.0" encoding="utf-16"?><ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyNamespace"><Person><Info>Welcome, Jeff</Info><Name>Jeff</Name></Person><Person><Info>Welcome, Frank</Info><Name>Frank</Name></Person></ArrayOfPerson>

    要让序列化后的XML更可读, 可以借助于XDocument , 测试代码:

            public void TestSerialize()
            {
                var persons = new List<Person>()
                {
                    new Person("Jeff"),
                    new Person("Frank")
                };
                string file = "out.xml";
                var dcs = new DataContractSerializer(typeof(List<Person>));
    
                // Serialize
                var sb = new StringBuilder();
                var xw = XmlWriter.Create(sb);
                dcs.WriteObject(xw, persons);
                xw.Close();
    
                var sw = new StreamWriter(file, false, Encoding.Unicode);
                var doc = XDocument.Parse(sb.ToString());
                //sw.Write(sb.ToString());
                sw.Write(doc.ToString());
                sw.Close();
    
                // Deserialize
                var xr = XmlReader.Create(file);
                var ps = (List<Person>)dcs.ReadObject(xr);
                Console.WriteLine(ps[1].Info);
            }

    结果:

    <ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyNamespace">
      <Person>
        <Info>Welcome, Jeff</Info>
        <Name>Jeff</Name>
      </Person>
      <Person>
        <Info>Welcome, Frank</Info>
        <Name>Frank</Name>
      </Person>
    </ArrayOfPerson>
  • 相关阅读:
    编程官方文档中常见的参数格式说明
    console.dir()和console.log()的区别
    JS中逗号运算符的用法
    Image 对象事件
    git已经删除了远程分支,本地仍然能看到
    Nginx初入
    WebApi设置SessionState为Required
    WebAPI2使用AutoFac依赖注入完整解决方案。
    CodeFirst时使用T4模板
    mysql5.7 java读取乱码
  • 原文地址:https://www.cnblogs.com/Freeway/p/5001130.html
Copyright © 2011-2022 走看看