c# replace \" characters

2019-02-04 04:28发布

I am sent an XML string that I'm trying to parse via an XmlReader and I'm trying to strip out the \" characters.

I've tried

.Replace(@"\", "")
.Replace("\\''", "''")
.Replace("\\''", "\"")

plus several other ways.

Any ideas?

6条回答
何必那么认真
2楼-- · 2019-02-04 04:42

Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the " characters, and so part of the actual XML data.

查看更多
疯言疯语
3楼-- · 2019-02-04 04:47

Replace(@"\""", "")

You have to use double-doublequotes to escape double-quotes within a verbatim string.

查看更多
Explosion°爆炸
4楼-- · 2019-02-04 04:50

Try it like this:

Replace("\\\"","");

This will replace occurrences of \" with empty string.

Ex:

string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");

This will result in:

the dog is my friend
查看更多
闹够了就滚
5楼-- · 2019-02-04 04:59

In .NET Framework 4 and MVC this is the only representation that worked:

Replace(@"""","")

Using a backslash in whatever combination did not work...

查看更多
做自己的国王
6楼-- · 2019-02-04 04:59
\ => \\ and " => \"

so Replace("\\\"","")

查看更多
走好不送
7楼-- · 2019-02-04 05:03

Were you trying it like this:

string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");

? If so, that's the problem - Replace doesn't change the original string, it returns a new string with the replacement performed... so you'd want:

string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");

Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:

string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");

(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)

查看更多
登录 后发表回答