.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>

 

posted @ 2015-11-27 16:45  ☆大森林☆  阅读(1179)  评论(0编辑  收藏  举报