为什么当我从XML文档中读取时,我会得到\ r \ n \ n \ n \ n等等?

时间:2011-05-12 16:06:42

标签: c# xml escaping

我理解这些是转义字符,但我如何从XML文档中读取并忽略它们?顺便说一句,我正在使用XmlDocument

3 个答案:

答案 0 :(得分:2)

您从文件中读取的字符串不包含"\r\n"。这些是escape sequences'\r''\n'分别代表一个回车符和换行符,它们形成一个换行符。

但是,如果您在字符串处查看VS调试器,则可能会看到转义序列而不是实际的换行符。来自MSDN

  

注意   在编译时,逐字字符串将转换为具有所有相同转义序列的普通字符串。因此,如果在调试器监视窗口中查看逐字字符串,您将看到编译器添加的转义字符,而不是源代码中的逐字字符。例如,逐字字符串@"C:\files.txt"将在观察窗口中显示为"C:\\files.txt"

示例:

var mystring = "Hello\r\nWorld";

Console.Write(mystring);

输出:

Hello
World

如果你真的想摆脱字符串中的换行符,你可以使用正则表达式:

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

// result == "Hello World";

答案 1 :(得分:0)

答案取决于您从文本文件中读取的具体程度以及您最终要完成的任务。

这是一个非常简单的解决方案:

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

答案 2 :(得分:0)

您可以对文件内容执行string.Replace,如下所示:

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