How do I use complex character replacement in C #?

I am trying to replace inside a string

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

      

and

]]></output>
</response>

      

with nothing. The problem I'm running into is that the <> and "characters interact within the replacement. The meaning is not reading these lines as a complete string together, as one, but breaking the string when it comes to <> or" This is what I have, but I know this is wrong:

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

      

What would be the correct code to get the replacement to see these lines as a string?

+3


source to share


2 answers


The string will never change. The method Replace

works like this:

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

      

However, the real issue is how to handle the XML response data.




You should rethink your approach to handling incoming XML by replacing a string. Just get content CDATA

using the standard XML library. It is so simple:

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

      

CDATA will already be removed. This tutorial will focus more on working with XML documents in C #.

+4


source


Given your document structure, you can simply say something like this:

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 ) ;

      

And see the expected results on the console:



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

      

If your XML document is more complex, you can easily select the desired node (s) using an XPath query, like this:

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

      

0


source







All Articles