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

2019-08-17 19:23发布

问题:

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', '');


标签: c# xml escaping