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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With