C#String.Replace双引号和文字

时间:2008-11-12 22:17:21

标签: c# xml

我对c#很新,所以这就是我在这里问的原因。

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

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:要在原始字符串中包含引号,您需要将其加倍。

这是重要的信息,现在尝试这种方法......也没有运气 这里有双引号发生的事情。你们所建议的概念都是可靠的,但这里的问题是处理双引号,看起来我需要做一些额外的研究来解决这个问题。如果有人想出一些东西,请发一个答案。

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

4 个答案:

答案 0 :(得分:21)

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>

P.S。

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

答案 1 :(得分:2)

字符串和正则表达式都使用\进行转义。正则表达式会看到字符\后跟",并认为这是一个字面上的转义。试试这个:

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

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

  

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

答案 2 :(得分:2)

根本没有理由使用正则表达式...这比你需要的要重得多。

string xmlSample = "blah blah blah";

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

答案 3 :(得分: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中拥有了该元素,就可以很容易地搜索并获取该元素中的元素的值和名称。

尝试一下,在检索WebServices响应时以及在XML文件中将某些内容存储为小型应用程序的设置时,我会大量使用它。

相关问题