2008-11-12 76 views
14

我对c#很新,所以这就是为什么我在这里问这个问题。C#String.Replace双引号和文字

我正在使用一个Web服务,该服务返回一长串XML值。因为这是一个字符串,所有的属性都逃过了双引号

string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>" 

这是我的问题。我想做一个简单的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> 

MizardX:?要包括你需要加倍原始字符串的报价。

这是重要的信息,现在想这种做法......没有运气或者 有一些事情在这里的双引号。的概念大家建议是坚实的,但这里的问题是处理双引号,它看起来像我需要做一些addit离子研究来解决这个问题。如果有人提出了一些问题,请发表一个答案。

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>" 
+0

绝对不要在这里使用的正则表达式,只需使用替换功能 – Domenic 2008-11-12 22:42:15

+0

看到最后的答案 - 你已经完成你想要的东西,这就是你看着它被搞乱您的方式 – 2008-11-12 23:22:22

回答

20

在C#下面的语句

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> 

附:

  1. 斜杠(\)是在C#中默认转义符
  2. 忽略斜杠,使用@在字符串的开头
  3. 如果使用@,转义字符是双引号(“)
2

两个字符串和正则表达式使用\转义。正则表达式将看到字符\,然后是",并认为这是一个字面上的逃避。试试这个:

Regex rgx = new Regex("\\\\\""); 
string strip = rgx.Replace(xmlSample, "\""); 

你也可以在C#中使用原始字符串(也称为veratim字符串)。它们的前缀为@,所有反斜杠都视为普通字符。要在原始字符串中包含报价,您需要将其加倍。

Regex rgx = new Regex(@"\""")
string strip = rgx.Replace(xmlSample, @"""");

2

没有理由使用正则表达式在所有...这比你所需要的更重了很多。

string xmlSample = "blah blah blah"; 

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

如果您正在获取XML字符串,为什么不使用XML而不是字符串?

,你将有机会获得所有的元素和属性,它会更简单,速度极快,如果在你的榜样使用System.Xml命名空间

您得到这个字符串:

string xmlSample = "<root><item att1=\"value\" att2=\"value2\" /></root>"; 

所有你需要做的是,字符串转换成XML文档,并使用它,如:

System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); 
xml.LoadXml(xmlSample); 

System.Xml.XmlElement _root = xml.DocumentElement; 

foreach (System.Xml.XmlNode _node in _root) 
{ 
    Literal1.Text = "<hr/>" + _node.Name + "<br/>"; 
    for (int iAtt = 0; iAtt < _node.Attributes.Count; iAtt++) 
     Literal1.Text += _node.Attributes[iAtt].Name + " = " + _node.Attributes[iAtt].Value + "<br/>"; 
} 
在ASP

。NET这将输出到Literal1类似:

item 
att1 = value 
att2 = value2 

一旦你有一个XmlElement的元素,这是很容易搜索和获取值和名称什么是在该元素。

试试看,检索Web服务的响应时,我用了很多,当我保存在一个XML文件的东西作为例如一个小的应用程序设置。