A simpler way to serialize a C # class as XML text

While trying to answer another question, I serialized a C # object for an XML string. It was surprisingly difficult; this was the shortest piece of code I could come up with:

var yourList = new List<int>() { 1, 2, 3 }; var ms = new MemoryStream(); var xtw = new XmlTextWriter(ms, Encoding.UTF8); var xs = new XmlSerializer(yourList.GetType()); xs.Serialize(xtw, yourList); var encoding = new UTF8Encoding(); string xmlEncodedList = encoding.GetString(ms.GetBuffer()); 

The result is in order:

 <?xml version="1.0" encoding="utf-8"?> <ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <int>1</int> <int>2</int> <int>3</int> </ArrayOfInt> 

But the fragment is more complex than I think. I can't believe what you need to know about coding and a MemoryStream for this simple task.

Is there a shorter way to serialize an object into an XML string?

+8
c # xml xml-serialization
Nov 15 '09 at 19:26
source share
3 answers

A bit shorter :-)

 var yourList = new List<int>() { 1, 2, 3 }; using (var writer = new StringWriter()) { new XmlSerializer(yourList.GetType()).Serialize(writer, yourList); var xmlEncodedList = writer.GetStringBuilder().ToString(); } 

Although there is a flaw in this previous approach, which is worth pointing out. It will generate the utf-16 header as we use StringWriter so that it is not exactly equivalent to your code. To get the utf-8 header, we must use MemoryStream and XmlWriter , which is an additional line of code:

 var yourList = new List<int>() { 1, 2, 3 }; using (var stream = new MemoryStream()) { using (var writer = XmlWriter.Create(stream)) { new XmlSerializer(yourList.GetType()).Serialize(writer, yourList); var xmlEncodedList = Encoding.UTF8.GetString(stream.ToArray()); } } 
+19
Nov 15 '09 at 19:33
source share
— -

Write down an extension method or a wrapper class / function to encapsulate the fragment.

0
Nov 15 '09 at 19:30
source share

You don't need a MemoryStream , just use a StringWriter :

 var yourList = new List<int>() { 1, 2, 3 }; using (StringWriter sw = new StringWriter()) { var xs = new XmlSerializer(yourList.GetType()); xs.Serialize(sw, yourList); string xmlEncodedList = sw.ToString(); } 
0
Nov 15 '09 at 19:33
source share



All Articles