Skip to content

Instantly share code, notes, and snippets.

@micolous
Last active December 31, 2015 02:49
Show Gist options
  • Save micolous/7923137 to your computer and use it in GitHub Desktop.
Save micolous/7923137 to your computer and use it in GitHub Desktop.
Fix .NET XML serialisation bugs by preventing it from passing XML 1.1-only entities in XML 1.0. This is a replacement for the use of the String class.
/// <summary>
/// Prevents .NET's XML serialiser from outputting XML 1.0-invalid entities.
///
/// Even though none of the .NET Framework supports XML 1.1, it still returns XML 1.1-only
/// entities (like &#x1B;).
///
/// This class acts as a wrapper around strings to automatically remove those unsafe escape
/// characters from the string before it is passed to the XML serialiser classes.
///
/// In order to use, simply replace instances of the "string" type in your serialised objects
/// with "XmlString". This will automatically filter out the characters silently in the
/// background.
/// </summary>
[XmlType("string", Namespace = "http://www.w3.org/2001/XMLSchema")]
public class XmlString
{
private string value;
[XmlText()]
public string Value
{
get
{
return this.value;
}
set
{
this.value = filterString(value);
}
}
public XmlString()
{
// XML serialiser needs a no-args constructor.
}
public XmlString(string value)
{
this.value = filterString(value);
}
private static string filterString(string input)
{
string output = "";
foreach (char c in input)
{
// Filter out bad XML characters.
if (c < '\x20' && c != '\x09' && c != '\x0A' && c != '\x0D')
// No control characters but TAB, LF and CR are allowed
continue;
if (c > '\xD7FF' && c < '\xE000')
continue;
output += c;
}
return output;
}
#region string conversion operators
public static implicit operator string(XmlString value)
{
return value.Value;
}
public static implicit operator XmlString(string value)
{
return new XmlString(value);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment