Tuesday, January 23, 2007

C# : XML in a C# string

Note: "Left quote" replaced by #, "Right quote" replaced by ^

How do you do this? It has quotes, slashes etc. e.g.

string zzz = "#employees xsi="http://www.w3.org/2001/XMLSchema-instance"^#employee-record^#employee-id^00001#/EMPLOYEE-ID^#employee-from^01 10 2006#/EMPLOYEE-FROM^#employee-to^01 11 2006#/EMPLOYEE-TO^#employee^#employee-id^00001#/EMPLOYEE-ID^#employee-name^Washington#/EMPLOYEE-NAME^#employee-firstname^George#/EMPLOYEE-FIRSTNAME^#employee-dob^01 01 1930#/EMPLOYEE-DOB^#/employee^#/EMPLOYEE-RECORD^#/employees^";

won't compile.

You could put a "@" in front to make it a verbatim string literal but it still won't compile.

The trick is to make each quote (") a double quote ("") e.g.

string zzz = @"#employees xsi=""^#employee-record^#employee-id^00001#/EMPLOYEE-ID^#employee-from^01 10 2006#/EMPLOYEE-FROM^#employee-to^01 11 2006#/EMPLOYEE-TO^#employee^#employee-id^00001#/EMPLOYEE-ID^#employee-name^Washington#/EMPLOYEE-NAME^#employee-firstname^George#/EMPLOYEE-FIRSTNAME^#employee-dob^01 01 1930#/EMPLOYEE-DOB^#/employee^#/EMPLOYEE-RECORD^#/employees^";

which does compile.

Enjoy!

No comments: