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?
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);
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/
精彩评论