我对c#很新,所以这就是我在这里问的原因.
我正在使用一个返回长字符串XML值的Web服务.因为这是一个字符串,所有属性都转义了双引号
string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"
Run Code Online (Sandbox Code Playgroud)
这是我的问题.我想做一个简单的string.replace.如果我在PHP中工作,我只需要运行strip_slashes().
但是,我在C#,我不能为我的生活弄清楚.我不能写出我的表达式来替换双引号("),因为它终止了字符串.如果我逃避它,那么它的结果不正确.我做错了什么?
string search = "\\\"";
string replace = "\"";
Regex rgx = new Regex(search);
string strip = rgx.Replace(xmlSample, replace);
//Actual Result <root><item att1=value att2=value2 /></root>
//Desired Result <root><item att1="value" att2="value2" /></root>
Run Code Online (Sandbox Code Playgroud)
MizardX:要在原始字符串中包含引号,您需要将其加倍.
这是重要的信息,现在尝试这种方法......没有运气.这里有双引号发生的事情.你们所建议的概念都是可靠的,但这里的问题是处理双引号,看起来我需要做一些额外的研究来解决这个问题.如果有人想出一些东西请发一个答案.
string newC = xmlSample.Replace("\\\"", "\"");
//Result <root><item att=\"value\" att2=\"value2\" /></root>
string newC = xmlSample.Replace("\"", "'");
//Result newC "<root><item att='value' att2='value2' /></root>"
Run Code Online (Sandbox Code Playgroud)
ala*_*ala 21
C#中的以下语句
string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"
Run Code Online (Sandbox Code Playgroud)
实际上会存储该值
<root><item att1="value" att2="value2" /></root>
Run Code Online (Sandbox Code Playgroud)
而
string xmlSample = @"<root><item att1=\""value\"" att2=\""value2\"" /></root>";
Run Code Online (Sandbox Code Playgroud)
有价值的
<root><item att1=\"value\" att2=\"value2\" /></root>
Run Code Online (Sandbox Code Playgroud)
对于第二种情况,您需要用空字符串替换斜杠(),如下所示
string test = xmlSample.Replace(@"\", string.Empty);
Run Code Online (Sandbox Code Playgroud)
结果将是
<root><item att1="value" att2="value2" /></root>
Run Code Online (Sandbox Code Playgroud)
PS
\)是C#中的默认转义字符