Search code examples
c#xmlasp.net-mvcescapingexport-to-excel

Delimiting double quotes for replacing XML characters


I am using a template Excel Export class which I found on CodeProject here

and within the class there is a method for replacing certain characters to make them safe for Excel, however the following line seems to be tripping up the system, since it is removing the delimited \" quote and replacing it with a single double quote.

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

If I delimit this again, to:

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

it defeats the purpose of the replacement, and if I leave it as it is, the rest of the class trips up because it is an unclosed string. Has anyone come across this before or got any ideas to get around this?

Thanks, Steve


Solution

  • I strongly suggest that you don't just use this article's code. It looks like it's not being shown correctly (I suspect it should be Replace("\"", """), but even if it were correct, it wouldn't be good code.

    Instead, use an XML API - LINQ to XML is very easy to use. That way you don't need to do any of the XML escaping yourself.

    You should almost never create XML documents by treating them as simple text. Instead, always use an XML API, which is a much cleaner way of making sure you end up creating valid XML.