6

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);
xar
  • 1,429
  • 2
  • 17
  • 29

2 Answers2

5

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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

Community
  • 1
  • 1
Laoujin
  • 9,962
  • 7
  • 42
  • 69