Preserve carriage return when using XDocument.Parse
Asked Answered
M

2

8

I have an application that is sensitive to a carriage return being \r\n or \n. I'm passing around a value in XML and when I parse it using XDocument the carriage retrun value is being converted to \n and I'm trying to find a way to keep it preserved as \r\n.

string myVal = "1234\r\nabcd";
string xmlText = "<doc>" + myVal + "</doc>";
XDocument xDoc = XDocument.Parse(xmlText);
Console.WriteLine("result=" + (xDoc.Element("doc").Value == myVal));
Console.WriteLine("result=" + (xDoc.Element("doc").Value == myVal.Replace("\r\n", "\n")));

Results:

result=False
result=True
Macegan answered 3/3, 2010 at 6:32 Comment(0)
P
3

Passing LoadOptions.PreserveWhitespace to XDocument.Parse is supposed to preserve insignificant whitespace from but from the community content at the bottom it appears not to be the case.

Can you load into the XDocument using an XmlReader instead? That may offer much more flexibility.

Proline answered 3/3, 2010 at 6:37 Comment(2)
Yeah I tried the PreserveWhiteSpace option with no joy. I'd thought about XmlReader but it seems like overkill to use a reader on a string. If there's no elegant way I'll probably just get by with a search and replace on the value I get from the Parse.Macegan
LoadOptions.PreserveWhitespace is not workingAnticlinorium
S
0

I used the following method after parsing:

XDocument xDocu = XDocument.Parse(xDataString);

foreach (XElement xEl in xDocu.Descendants()) {
  if (xEl.HasElements == false && xEl.Value != null) {
     xEl.Value = xEl.Value.Replace("\n", "\r\n");
   }
}
Sharkey answered 6/6, 2023 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.