开发者

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

开发者 https://www.devze.com 2023-03-05 16:53 出处:网络
I understand these are escape characters but how do I read from a XML document and ignore them? I\'m using XmlDocu开发者_如何学Pythonment, by the way.The string you read from the file does not literal

I understand these are escape characters but how do I read from a XML document and ignore them? I'm using XmlDocu开发者_如何学Pythonment, by the way.


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";


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号