我将如何使用System.Xml.Serialization对此.net类型进行注释以对以下XML进行序列化/反序列化?

时间:2017-01-20 04:10:45

标签: c# xml .net-4.0 xmlserializer

类型:

public class Foo
{
    public string Bar { get; set; }
    public string Fred { get; set; }
}

实例

Foo x = new Foo { Bar = "Hi", Fred = "hey yourself" };

XML:

<Foo>
   <Bar>Hi</Bar>
   <John>                         <!-- Note extra layer -->
       <Fred>hey there</Fred>
   </John>
</Foo>

请注意额外的John代码,但不为John创建特殊类型。如果我无法对其进行注释,那么我该如何以编程方式控制序列化过程。

1 个答案:

答案 0 :(得分:0)

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Runtime;
using System.Runtime.InteropServices;

namespace ConsoleApplication42
{
    class Program
    {

        static void Main(string[] args)
        {

            Foo x = new Foo { Bar = "Hi", Fred = "hey yourself" };
            //<Foo>
            //   <Bar>Hi</Bar>
            //   <John>                         <!-- Note extra layer -->
            //       <Fred>hey there</Fred>
            //   </John>
            //</Foo>

            XElement foo = new XElement("Foo", new object[] {
                new XElement("Bar", x.Bar),
                new XElement("John", new XElement("Fred", x.Fred))
            });

        }
    }
    public class Foo
    {
        public string Bar { get; set; }
        public string Fred { get; set; }
    }

}