Reputation: 2321
I am serializing a string from a multiline text box to an XML. Is send the line breaks and tabs to save in the XML so when I deserialize it, I get it back looking the same?
Example - The textbox will look like:
Hello JohnDoe,
This is a message
...
Somelines....
Thank you,
...
End
When I serialize this and then deserialize it, the textbox gets populated like:
Hello JohnDoe,This is a message..Some lines....Thank you,...End
It doesn't have to be really pretty, I'm just trying to come up with a good way to get it back in a better format. Thanks.
Okay so the code i have is as follows:
public void SerializeToXML(List<Report> newReport)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Report>));
//XmlWriterSettings serializer_settings = new XmlWriterSettings();
//serializer_settings.Indent = true;
//serializer_settings.NewLineOnAttributes = true;
TextWriter textWriter = new StreamWriter(xmlPath);
serializer.Serialize(textWriter, newReport);
textWriter.Close();
}
Where Report
is just a class with some string attributes. The commented lines are somethings I was trying to accomplish my goal.
Report class code:
public class Report
{
public string name
{ get; set; }
public string email
{ get; set; }
public string defectID
{ get; set; }
public string fixedBuild
{ get; set; }
public string description
{ get; set; }
[XmlIgnore]
public string messageBody
{ get; set; }
private static readonly XmlDocument _xmlDoc = new XmlDocument();
[XmlElement("messageBody")]
public XmlCDataSection TextCData
{
get
{
return _xmlDoc.CreateCDataSection(messageBody);
}
set
{
messageBody = value.Data;
}
}
}
the output remains the same (no whitespace formatting).
Upvotes: 2
Views: 4456
Reputation: 16472
This article seems to offer a valid solution. Also check out this answer here.
Hard to give good advice without seeing your code.
EDIT
You could add it manually.
Or you might be able to get by with something like this (untested, modified from this question):
public class Report
{
[XmlAttribute("xml:space")]
public string spacing = "preserve";
}
this way it should get added automatically during serialization. However, if you can figure out a way to set an XmlAttribute that's not based off a field or property, that would be even better.
Upvotes: 1
Reputation: 726479
One way to preserve all whitespace in your XML is to use a CDATA
section. The details depend on the way you do your serialization. See this question for an explanation in a web service context. If you serialize manually, use XmlWriter.WriteCData
method.
Upvotes: 3