2

Is there a way i can preserve\r\n on XElement.Load().

  TextReader reader = new StringReader(rawInputString);//rawInputString is just text in html format
    XElement root = XElement.Load(reader);

Edit :

string  rawInputString =  "<Html><Body><p></p> \r\n <p></p>\r\n \r\n \r\n </Body></Html>";

After XELement.Load the output i want is the same when i do root.ToString() :

"<Html><Body><p></p> \r\n <p></p>\r\n \r\n \r\n </Body></Html>"

For Now it just cleans/removes up the \r\n

Malcolm
  • 1,801
  • 3
  • 21
  • 48

1 Answers1

6

This should do the trick:

XElement root = XmlElement.Load(reader, LoadOptions.PreserveWhitespace);

Check this article for more information: Preserving White Space while Loading or Parsing XML

In addition, callling the XElement.ToString() method will cause the XElement to apply its own formatting. In order to prevent that, you must call XElement.ToString(SaveOptions.DisableFormatting)

Sven
  • 21,903
  • 4
  • 56
  • 63
  • @Sven i think it will preserve only white sapce rt? – Malcolm Jun 20 '11 at 14:48
  • Line breaks are a form of whitespace, so it will preserve them as well. – Sven Jun 20 '11 at 14:49
  • Could you post an example of your XML, what you expect to happen, and what actually happens? I just tested it myself and it definitely does preserve newlines in non-significant whitepace. – Sven Jun 20 '11 at 15:06
  • 1
    I tested your sample, and PreserveWhitespace works for me. Note however that `ToString()` causes the XML to be reformatted, and if you want to prevent that, you must use `SaveOptions.DisableFormatting` (I've udated my answer accordingly) – Sven Jun 20 '11 at 15:18