Thursday, 23 October 2008

Parsing XML Escape Charcters

Here is some C# code i've used in the past to make any piece of text XML safe, and vice-versa. The logic applies across all languages. Remember to escape & first!

private string outputParseFields(string field)
{
    // Escape illegal chars. (escape '&' first!)
    field = field.Replace("&", "&");
    field = field.Replace("<", "<");
    field = field.Replace(">", ">");
    field = field.Replace("'", "'");
    field = field.Replace("\"", """);
 
    return (field);
}
 
private string inputParseFields(string field)
{
    // Escape illegal chars. (escape '&' first!)
    field = field.Replace("&", "&");
    field = field.Replace("<", "<");
    field = field.Replace(">", ">");
    field = field.Replace("'", "'");
    field = field.Replace(""", "\"");
 
    return (field);
} 

No comments: