为什么当我从XML文档中读取时,我会得到\r\r\\\<br/>\\\<br/> etc等吗? [英] Why when I read from an XML document do I get \r\r\n\n etc etc?

查看:391
本文介绍了为什么当我从XML文档中读取时,我会得到\r\r\\\<br/>\\\<br/> etc等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这些是转义字符,但是如何从XML文档中读取并忽略它们?我正在使用 XmlDocument

解决方案

字符串你从文件中读取的字符不包含\\\\。那些是转义序列'\r''\\\
'
分别表示回车符和新行字符,这样就形成一个换行符。



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


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


示例:

  var mystring =Hello\r\\\
World;

Console.Write(mystring);

输出:

 
你好
世界






如果你真的想摆脱例如,您可以使用正则表达式:

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

// result ==Hello World;


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.

解决方案

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

这篇关于为什么当我从XML文档中读取时,我会得到\r\r\\\<br/>\\\<br/> etc等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆