user1976596
user1976596

Reputation:

Remove the escape sequence '\' from string to convert it to XmlDocument

I have a web service which returns a struct object, so I get the response as the following XML string. Now I need to load it into XmlDocument object but how do I get rid of the escape sequences in the string. The '\' with every '"' is causing error.

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Quote xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://tempuri.org/\">
<price>19656</price>
</Quote>

Upvotes: 8

Views: 62918

Answers (4)

user3931102
user3931102

Reputation: 69

You'll want to use Regex.Unescape method.

String unescapedString = Regex.Unescape(textString);

However, becareful that the Regex.Unescape doesn't un-escape ". According to the documentation, it does the following:

..by removing the escape character ("") from each character escaped by the method. These include the , *, +, ?, |, {, [, (,), ^, $,., #, and white space characters. In addition, the Unescape method unescapes the closing bracket (]) and closing brace (}) characters.

Upvotes: 6

Shreyas Sawant
Shreyas Sawant

Reputation: 45

You can try escaping in verbatim strings

xmlStr= xmlStr.Contains("\\") ? xmlStr.Replace("\\", @"\"") : xmlStr;

Upvotes: 1

Mirko
Mirko

Reputation: 2466

Use Regex.Unescape method.

String unescapedString = Regex.Unescape(textString);

Upvotes: 24

JLRishe
JLRishe

Reputation: 101680

So the webservice is returning the string with actual backslashes in it? If so, I would say there's a problem with that webservice you're using, but you should be able to get around it by doing this:

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

Upvotes: 4

Related Questions