views:

260

answers:

2

My application receive strings from outside and construct an XML document

string fromOutside = "\0";
XAttribute a = new XAttribute(fromOutside);

when the attribute value contains null character then I got exception when trying to save XML to the disk (when it goes into XmlWriter)

System.ArgumentException : '.', hexadecimal value 0x00, is an invalid character.

Even the SecurityElement class doesn't help

Assert.IsFalse(SecurityElement.IsValidAttributeValue("\0"));

What is the best way to construct the XML document from strings which may contain such invalid characters like null character etc?

+1  A: 

You cannot escape non-printing characters such as NULL because there's no equivalent escape character defined for them. You cannot represent it unless you have HEX or Base64 encoded fragments. So you could either Base64 encode the string or make sure it does not contain non-printing characters.

string fromOutside = "\0";
string base64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(fromOutside));
XAttribute a = new XAttribute("id", base64Encoded);
Darin Dimitrov
So in my case the only way is to parse the string and remove null characters, isn't it? :-(
Petr Felzmann
No, you could also Base64 encode the string: `Convert.ToBase64String(Encoding.UTF8.GetBytes(fromOutside))`
Darin Dimitrov
Base64 is not an option for me, because I have to keep the string readable in the result XML. Example of the string can be "\0My\0 fancy val\0ue\0\0\0".
Petr Felzmann
Well, then you will have to roll your own function that will replace every non-printable character with `\\CODE`.
Darin Dimitrov
A: 

I found also good blog post where author provided the code for removing invalid non-printable characters from strings

http://seattlesoftware.wordpress.com/2008/09/11/hexadecimal-value-0-is-an-invalid-character/

Petr Felzmann