C# 从字符串中删除转义序列 '\' 以将其转换为 XmlDocument
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14810215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove the escape sequence '\' from string to convert it to XmlDocument
提问by
I have a web service which returns a struct object, so I get the response as the following XML string. Now I need to load it into XmlDocument object but how do I get rid of the escape sequences in the string. The '\' with every '"' is causing error.
我有一个返回 struct 对象的 Web 服务,因此我得到以下 XML 字符串的响应。现在我需要将它加载到 XmlDocument 对象中,但是如何摆脱字符串中的转义序列。带有每个 '"' 的 '\' 导致错误。
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Quote xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://tempuri.org/\">
<price>19656</price>
</Quote>
回答by JLRishe
So the webservice is returning the string with actual backslashes in it? If so, I would say there's a problem with that webservice you're using, but you should be able to get around it by doing this:
那么网络服务正在返回带有实际反斜杠的字符串吗?如果是这样,我会说您正在使用的网络服务存在问题,但您应该能够通过这样做来解决它:
xmlStr = xmlStr.Replace("\\"", "\"");
回答by Mirko
回答by user3931102
Regex.Unescapedoesn't un-escape "
. According to the documentation, it does the following:
Regex.Unescape不会取消转义"
。根据文档,它执行以下操作:
"..by removing the escape character ("\") from each character escaped by the method. These include the \, *, +, ?, |, {, [, (,), ^, $,., #, and white space characters. In addition, the Unescape method unescapes the closing bracket (]) and closing brace (}) characters."
"..通过从该方法转义的每个字符中删除转义字符 ("\")。这些包括 \、*、+、?、|、{、[、(,)、^、$、.、#、和空白字符。此外,Unescape 方法对右方括号 (]) 和右大括号 (}) 字符进行转义。”
回答by Shreyas Sawant
You can try escaping in verbatim strings
您可以尝试逐字字符串转义
xmlStr= xmlStr.Contains("\") ? xmlStr.Replace("\", @"\"") : xmlStr;