Why when I read from an XML document do I get \r\r\n\n etc etc?

柔情痞子 提交于 2019-12-25 08:53:02

问题


I understand these are escape characters but how do I read from a XML document and ignore them? I'm using XmlDocument, by the way.


回答1:


The string you read from the file does not literally contain "\r\n". Those are escape sequences. '\r' and '\n' represent a carriage-return and new-line character, respectively, which form together a line break.

If you're looking with the VS debugger at the string, however, you may see the escape sequences instead of actual line breaks. From MSDN:

Note At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string @"C:\files.txt" will appear in the watch window as "C:\\files.txt".

Example:

var mystring = "Hello\r\nWorld";

Console.Write(mystring);

Output:

Hello
World

If you actually want to get rid of line breaks in a string, you can, for example, use a regex:

var result = Regex.Replace(mystring, @"\s+", " ");

// result == "Hello World";



回答2:


The answer depends on how specifically you're reading from the text file and what you're trying to accomplish in the end.

Here's a very simple solution:

StringBuilder sb = new StringBuilder();
using(var sr = new System.IO.StreamReader('path/to/your/file.txt'))
{
  while(true)
  {
     string line = sr.ReadLine();
     // if this is the final line, break out of the while look
     if(line == null)
        break;
     // append this line to the string builder
     sb.Append(line);
  }
  sr.Close();
}

// the sb instance hold all the text in the file, less the \r and \n characters
string textWithoutEndOfLineCharacters = sb.ToString();



回答3:


You can do a string.Replace on the content of the file like so:

string contents = File.ReadAllText('myfile.txt');
contents = contents.Replace('\n', '');


来源:https://stackoverflow.com/questions/5980968/why-when-i-read-from-an-xml-document-do-i-get-r-r-n-n-etc-etc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!