While working on a simple web API, I needed a way to serialize an object (using the XML serializer) to a string so I could return it as an API response. Unfortunately, there’s no Serialize() override for returning a string value. Instead, you’ll have to use a MemoryStream object and the System.Text.Encoding class.
1 2 3 4 | XmlSerializer xs = new XmlSerializer(typeof(YourObject)); MemoryStream ms = new MemoryStream(); xs.Serialize(ms, instanceOfYourObject); Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); |
Perhaps an extension method would be good in this case.
1 2 3 4 5 | public static string GetXmlString(this XmlSerializer xs, object obj) { MemoryStream ms = new MemoryStream(); xs.Serialize(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } |
1 2 | XmlSerializer xs = new XmlSerializer(typeof(YourObject)); Console.WriteLine(xs.GetXmlString(instanceOfYourObject)); |
0 Responses to “XML Serialize an object to a string”
Leave a Reply