c# - 我将如何使用 System.Xml.Serialization 注释此 .net 类型以序列化/反序列化到/从以下 XML

标签 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 创建特殊类型。如果我无法对其进行注释,我该如何以编程方式控制序列化过程。

最佳答案

试试这个:

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; }
    }

}

关于c# - 我将如何使用 System.Xml.Serialization 注释此 .net 类型以序列化/反序列化到/从以下 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41755971/

相关文章:

c# - 找到标志枚举长度的有效方法?

.net-4.0 - 为什么 .net 4.0 将所有这些内容写入 DebugView?

c# - 加载相关对象时出现异常。 Entity Framework

c# - 删除超过一定天数的文件

c# - 如何获得 google-cardboard 相机 FOV?

JavaScript——这个单选按钮被选中了吗?

c# - 如何将 xmlReader 从子元素移动到父元素?

java - 使用 xml 配置来休息 Spring bean

c# - ConcurrentDictionary<> 在单线程时的表现误区?

c# - 在 ASP.NET aspx 页面中使用 `<%= "{0}, {1 }", arg1, arg2 %>` 代替 `<%= string.Format("{0}, {1 }", arg1, arg2) %>` 是否有效