如何在C#中使用替换为棘手字符?

如何在C#中使用替换为棘手字符?,c#,string,replace,C#,String,Replace,我试图在一个字符串内替换 <?xml version="1.0" encoding="UTF-8"?> <response success="true"> <output><![CDATA[ 及 ]> 一无所有。 我遇到的问题是字符和“字符在替换中相互作用。这意味着,它不是将这些行作为一个完整的字符串一起读取,而是在遇到or时将字符串断开”。这是我所拥有的,但我知道这是不对的: String responseString = reader.Read

我试图在一个字符串内替换

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

]>
一无所有。 我遇到的问题是字符和“字符在替换中相互作用。这意味着,它不是将这些行作为一个完整的字符串一起读取,而是在遇到or时将字符串断开”。这是我所拥有的,但我知道这是不对的:

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

要让replace将这些行视为字符串,正确的代码是什么?

字符串永远不会改变。
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已被删除。将教授更多关于在C#中使用XML文档的知识。

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

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 ) ;
如果XML文档稍微复杂一点,则可以使用XPath查询轻松选择所需的节点,因此:

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

您是否考虑过像
和#x5564?这可能是你需要处理的其他事情。你可能想改为。为什么不使用正则表达式呢@user3444160这篇文章解释了原因
The response indicated success.
response content: The output is some arbitrary text and it may be found here.
string content = document.SelectSingleNode( @"/response/output" ).InnerText;