C# 字符串。替换双引号和文字

C# 字符串。替换双引号和文字,c#,xml,C#,Xml,我对c#相当陌生,所以我在这里问这个问题 我正在使用一个返回一长串XML值的web服务。因为这是一个字符串,所以所有属性都用双引号转义 string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>" string xmlSample=“” 这是我的问题。我想做一个简单的string.replace。如果我使用PHP,我会运行strip_slashes() 然而,我在C#,我

我对c#相当陌生,所以我在这里问这个问题

我正在使用一个返回一长串XML值的web服务。因为这是一个字符串,所以所有属性都用双引号转义

string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"
string xmlSample=“”
这是我的问题。我想做一个简单的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>
string search=“\\\”;
字符串replace=“\”;
正则表达式rgx=新正则表达式(搜索);
string strip=rgx.Replace(xmlSample,Replace);
//实际结果
//期望结果
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>"
string newC=xmlSample.Replace(“\\\”,“\”);
//结果
字符串newC=xmlSample.Replace(“\”,“”);
//结果newC“”

字符串和正则表达式都使用
\
进行转义。正则表达式将看到字符
\
后跟
,并认为这是文字转义。请尝试以下操作:

Regex rgx = new Regex("\\\\\"");
string strip = rgx.Replace(xmlSample, "\"");
您也可以在C#中使用原始字符串(也称为veratim字符串)。它们的前缀为
@
,所有反斜杠都被视为普通字符。要在原始字符串中包含引号,您需要将其加倍

Regex rgx=new Regex(@“\”)

string strip=rgx.Replace(xmlSample,@“”);


根本没有理由使用正则表达式……它比您需要的要重得多

string xmlSample = "blah blah blah";

xmlSample = xmlSample.Replace("\\\", "\"");

如果您得到的是XML字符串,为什么不使用XML字符串呢

您将可以访问所有元素和属性,如果使用System.Xml名称空间,将会更加容易和非常快

在您的示例中,您得到以下字符串:

string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>";
一旦在XmlElement中有了元素,就可以很容易地搜索和获取该元素中的值和名称


试一试,我在检索Web服务响应时以及在XML文件中存储某些内容作为小型应用程序的设置时(例如)经常使用它

结果将是

<root><item att1="value" att2="value2" /></root>

附言

  • 斜杠(
    \
    )是C语言中的默认转义字符#
  • 若要忽略斜杠,请在字符串开头使用@
  • 如果使用@,则转义字符为双引号(“)

  • 绝对不要在这里使用正则表达式;只需使用替换功能!看最后一个答案——你已经完成了你想要的,是你看待它的方式把你搞砸了。我同意,我甚至看不到这里的问题。斜杠不是字符串中的真实字符,它们是转义标记!谢谢大家,我只是需要关于文字等的解释。我在答案上做了标记。它工作正常,就像我预期的那样,我用正确的字符串替换了错误的字符串…grrrr。我要更正确地说,a没有转义字符,特殊字符
    {
    }
    通过加倍转义。
    item
    att1 = value
    att2 = value2
    
    string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"
    
    <root><item att1="value" att2="value2" /></root>
    
    string xmlSample = @"<root><item att1=\""value\"" att2=\""value2\"" /></root>";
    
    <root><item att1=\"value\" att2=\"value2\" /></root>
    
    string test = xmlSample.Replace(@"\", string.Empty);
    
    <root><item att1="value" att2="value2" /></root>