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是怎么做到的。