Indent text in xml serialization of string property?
I have a string property which will contain text with newlines. This text
has some of the properties of HTML text in that whitespace is disregarded.
If I serialize this type using XML serialization, the newlines are
serialized properly, but the indentation is "wrong". I want the
serialization process to indent the lines to keep the formatting of the
XML, since those whitespace characters will be disregarded later anyway.
Here's an example LINQPad program:
void Main()
{
var d = new Dummy();
d.Text = @"Line 1
Line 2
Line 3";
var serializer = new XmlSerializer(typeof(Dummy));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (var writer = new StringWriter())
{
serializer.Serialize(writer, d, ns);
writer.ToString().Dump();
}
}
[XmlType("dummy")]
public class Dummy
{
[XmlElement("text")]
public string Text
{
get;
set;
}
}
Actual output:
<?xml version="1.0" encoding="utf-16"?>
<dummy>
<text>Line 1
Line 2
Line 3</text>
</dummy>
Desired output:
<?xml version="1.0" encoding="utf-16"?>
<dummy>
<text>
Line 1
Line 2
Line 3
</text>
</dummy>
Is this possible? If so, how? I'd rather not do the hackish way of just
adding the whitespace in myself.
The reason for this is that this XML will be viewed and edited by people,
so I'd like for the initial output to be better formatted for them out of
the box.
No comments:
Post a Comment