I have xml that I read it to a table cell but it seems that when there is a new line it
change it with white space. How can I preserve my new line when I read the xml using C#.
var xmlDoc = XDocument.Load(new XmlTextReader(Server.MapPath("NSrc.xml")),
LoadOptions.PreserveWhitespace);
foreach (var descendant in xmlDoc.Descendants("NewsItem"))
{
var title = descendant.Element ("Title").Value;
TableRow rw = new TableRow();
TableCell cell = new TableCell();
var title = descendant.Element("Title").Value;
var summary = descendant.Element("Summary").Value;
cell.Text = title;
rw.Cells.Add(cell);
tbl.Controls.Add(rw);
rw = new TableRow();
cell = new TableCell();
cell.Text = summary;
rw.Cells.Add(cell);
tbl.Controls.Add(rw);
}
By setting PreserveWhitespace, you were trying a simple approach that “should work”. For most XML reading APIs, this works exactly as you’d expect, and any newline that occurs within an element’s data will be read back verbatim within your program (but beware that all other whitespace, including indentation ect will be included too).
However, the Load method, when used with an XmlReader, ignores the Preserve setting. D’oh.
If you instead Load from a Stream, it should preserve whitespace is asked to by the LoadOptions.
(I’ll leave it to others to decide whether or not preserving whitespace in this way is a good or evil approach. Encoding the newlines using CDATA would no doubt be more correct if you are in control of the source XML data. But it is an approach that will work, and I felt it only fair to let you know why it didn’t work as you expected)