My data entity contains a Dictionary, but XmlSerializer does not support them out of the box. So I decided to use DataContractSerializer. The problem is that I cannot get it to behave as I need.
I started with the following code:
public static string SerializeObject<T>(T serialisable)
{
var serializer = new DataContractSerializer(serialisable.GetType());
using (var writer = new StringWriter())
using (var stm = new XmlTextWriter(writer))
{
serializer.WriteObject(stm, serialisable);
return writer.ToString();
}
}
It seemed to work fine until I noticed that if I put "\r\n" in a string, it does not get serialized to XML entities. From my experience with XmlSerializer, I knew that I can set up XmlWriterSettings with NewLineHandling = NewLineHandling.Entitize. So I converted my code to the following:
public static string SerializeObject<T>(T serialisable)
{
var serializer = new DataContractSerializer(serialisable.GetType());
using (var writer = new StringWriter())
{
using (var stm = XmlWriter.Create(writer,
new XmlWriterSettings()
{
NewLineHandling = NewLineHandling.Entitize
}))
{
serializer.WriteObject(stm, serialisable);
return writer.ToString();
}
}
}
Now the problem is that I get an empty string. No exceptions, nothing - just an empty string. The stm variable holds XmlWellFormedWriter. Maybe it's not supported by DataContractSerializer?
Then I tried to enforce XmlTextWriter as follows:
public static string SerializeObject<T>(T serialisable)
{
var serializer = new DataContractSerializer(serialisable.GetType());
using (var writer = new StringWriter())
using (var stm = XmlWriter.Create(new XmlTextWriter(writer),
new XmlWriterSettings()
{
NewLineHandling = NewLineHandling.Entitize
}))
{
serializer.WriteObject(stm, serialisable);
return writer.ToString();
}
}
And this gets me back to where I started - I get back XML string, but again "\r\n" string is not translated to entities.
How do I make DataContractSerializer to entitize newlines and return XML as string?