如何序列化匿名类型对象到XML? [英] How to serialize Anonymous-typed Objects to XML?
问题描述
有序列化到一个XML字符串动态创建对象的任何可能的方式?
VAR foobar的=新{FOO =酒吧};
XML字符串= ConvertToXMLString(FOOBAR);
// XML应该是这样的:
//<富>巴≤; /富>
我能看看的XMLSerializer和DataContractSerializer的,但XMLSerializer的要求的对象类型,而DataContractSerializer的要求就需要被序列化属性的属性。
出于绝望,我转换的对象以JSON第一和JSON其转换为XML。
VAR foobar的=新{FOO =酒吧};
JavaScriptSerializer JS =新JavaScriptSerializer();
jsonString = js.Serialize(值);
//Json.NET在http://json.$c$cplex.com/
XmlDocument的DOC =(XmlDocument的)JsonConvert.DeserializeXmlNode(jsonString);
不使用标准的内置串行器,无; 的XmlSerializer
要求公共类型(该匿名类型的不是的),并且仅适用于读写成员(其中匿名类型的没有的)。 的DataContractSerializer
想要的属性(其匿名类型的没有的)。
坦率地说,最简单,最支持的固定在这里正式宣布POCO DTO匹配你是什么之后,又名:不使用匿名类型在这里。例如:
公共类MyDto {
公共字符串FOO {获取;集;}
}
...
VAR foobar的=新MyDto {FOO =酒吧};
另一种方法是的实际上的写自己的XML序列化。这......听起来并不很有趣。
Is there any possible way to serialize dynamically created object to an xml string?
var foobar = new { foo = "bar" };
string xml = ConvertToXMLString(foobar);
//xml should be something like :
//<foo>bar</foo>
I was able to take a look at XMLSerializer and DataContractSerializer but XMLSerializer requires the object type while DataContractSerializer requires attribute on the properties that needs to be serialized.
Out of desperation, I converted the object to JSON first and from JSON converted it to XML.
var foobar = new { foo = "bar" };
JavaScriptSerializer js = new JavaScriptSerializer();
jsonString = js.Serialize(values);
//Json.NET at http://json.codeplex.com/
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString);
Not using the standard inbuilt serializers, no; XmlSerializer
demands public types (which anonymous types aren't), and only works for read-write members (which anonymous types don't have). DataContractSerializer
wants attributes (which anonymous types don't have).
Frankly, the simplest and most supportable "fix" here is to formally declare a POCO DTO that matches what you are after, aka: don't use an anonymous type here. For example:
public class MyDto {
public string foo {get;set;}
}
...
var foobar = new MyDto { foo = "bar" };
The alternative would be essentially writing your own xml serializer. That... does not sound like fun.
这篇关于如何序列化匿名类型对象到XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!