Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用System.XML.Serialization注释此.net类型,以便与以下XML进行序列化/反序列化_C#_Xml_.net 4.0_Xmlserializer - Fatal编程技术网

C# 如何使用System.XML.Serialization注释此.net类型,以便与以下XML进行序列化/反序列化

C# 如何使用System.XML.Serialization注释此.net类型,以便与以下XML进行序列化/反序列化,c#,xml,.net-4.0,xmlserializer,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> <!-

类型:

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

}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
使用系统运行时;
使用System.Runtime.InteropServices;
命名空间控制台应用程序42
{
班级计划
{
静态void Main(字符串[]参数)
{
foox=newfoo{Bar=“Hi”,Fred=“hey yourself”};
//
//嗨
//                            
//嘿
//   
//
XElement foo=新XElement(“foo”,新对象[]{
新XElement(“Bar”,x.Bar),
新元素(“约翰”,新元素(“弗雷德”,x.Fred))
});
}
}
公开课Foo
{
公共字符串条{get;set;}
公共字符串Fred{get;set;}
}
}

john tag来自哪里?你的意思是想用其他自定义标记嵌套一个标记吗?这就是我想要额外标记的问题。我认为你应该使用XmlDocument并编写自己的代码,而不是使用XmlSerializer。这可能是您最后的选择谢谢,但我已经在使用System.Xml.Serialization,我的问题只是我正在序列化的一组更大类型的一个示例。我可以将其挂接到System.Xml.Serialization进程中吗?您必须编写一个自定义序列化程序。我从来没有写过。标准序列化程序通过类进行枚举,并在不存在的地方添加“John”。我不知道serilizer是怎么做到的。