Fm3
Fm3

Reputation: 55

Preserve new line when reading xml using C#

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);
}

Upvotes: 1

Views: 4811

Answers (2)

Jason Williams
Jason Williams

Reputation: 57952

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)

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273784

This is proper XML behaviour, newlines don't exist in XML. Some formatters may add them (again but maybe different) on output.

How can I preserve my new line when I read the xml

By packing your text in a CDATA element.


Edit

xmlDoc.Root.Add(new XCData("line1\nline2"));

You can retrieve this multi-line text as Root.Value

Upvotes: 6

Related Questions