【问题标题】:How to use replace with tricky characters in C#?如何在 C# 中使用棘手的字符替换?
【发布时间】:2015-05-28 17:42:36
【问题描述】:

我正在尝试在字符串中替换

<?xml version="1.0" encoding="UTF-8"?>
<response success="true">
<output><![CDATA[

]]></output>
</response>

什么都没有。 我遇到的问题是字符 和 " 字符在替换中相互作用。意思是,它不是将这些行作为一个完整的字符串一起读取,而是在涉及 或 " 时破坏字符串。这是我所拥有的,但我知道这是不对的:

String responseString = reader.ReadToEnd();
            responseString.Replace(@"<<?xml version=""1.0"" encoding=""UTF-8""?><response success=""true""><output><![CDATA[[", "");
            responseString.Replace(@"]]\></output\></response\>", "");  

获取替换以将这些行视为字符串的正确代码是什么?

【问题讨论】:

标签: c# string replace


【解决方案1】:

字符串永远不会改变。 Replace 方法的工作原理如下:

string x = "AAA";
string y = x.Replace("A", "B");
//x == "AAA", y == "BBB"

然而,真正的问题是如何处理 XML 响应数据。


您应该重新考虑通过字符串替换处理传入 XML 的方法。只需使用标准 XML 库获取 CDATA 内容。就这么简单:

using System.Xml.Linq;
...
XDocument doc = XDocument.Load(reader);
var responseString = doc.Descendants("output").First().Value;

CDATA 已被删除。 This tutorial 将教授更多关于在 C# 中使用 XML 文档的知识。

【讨论】:

    【解决方案2】:

    鉴于您的文档结构,您可以简单地说如下:

    string response = @"<?xml version=""1.0"" encoding=""UTF-8""?>"
                    + @"<response success=""true"">"
                    + @"  <output><![CDATA["
                    + @"The output is some arbitrary text and it may be found here."
                    + "]]></output>"
                    + "</response>"
                    ;
    XmlDocument document = new XmlDocument() ;
    document.LoadXml( response ) ;
    
    bool success ;
    bool.TryParse( document.DocumentElement.GetAttribute("success"), out success)  ;
    
    string content = document.DocumentElement.InnerText ;
    
    Console.WriteLine( "The response indicated {0}." , success ? "success" : "failure" ) ;
    Console.WriteLine( "response content: {0}" , content ) ;
    

    并在控制台上查看预期结果:

    The response indicated success.
    response content: The output is some arbitrary text and it may be found here.
    

    如果您的 XML 文档稍微复杂一点,您可以使用 XPath 查询轻松选择所需的节点,因此:

    string content = document.SelectSingleNode( @"/response/output" ).InnerText;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 2014-12-22
      • 1970-01-01
      相关资源
      最近更新 更多