Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Anonymous-typed Objects to 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);
like image 651
xar Avatar asked Aug 10 '12 05:08

xar


2 Answers

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.

like image 181
Marc Gravell Avatar answered Oct 18 '22 22:10

Marc Gravell


It can be done using reflection, check the second and third answer in this thread for code examples: Can I serialize Anonymous Types as xml?

MartinHN also blogged about this

like image 1
Laoujin Avatar answered Oct 18 '22 22:10

Laoujin