Hexadecimal value 0x…, is an invalid character

The document contains a control character that XML 1.0 does not allow.

The message, as .NET reports it
'\x01', hexadecimal value 0x01, is an invalid character. Line 1, position 8.

Why it happens

  • Control characters copied from a database or a binary field: 0x00 to 0x1F other than tab, line feed and carriage return.
  • Writing such a character with XmlWriter fails the same way, with is an invalid character.

How to fix it

Remove the characters before writing the XML (XmlConvert.IsXmlChar tells which are allowed), or put binary data in Base64. XmlReaderSettings.CheckCharacters = false only hides the problem from your own reader.

.NET throws an XmlSchemaValidationException at the first schema error unless XmlReaderSettings.ValidationEventHandler is set, which then receives every one with its line and position. A well-formedness error is an XmlException and ends reading whatever the settings.

The same problem in xmlvalid

xmlvalid validates with libxml2, which reports it as PCDATA invalid Char value. It checks the whole document in your browser and lists every schema error with its line and column, not only the first.

PCDATA invalid Char value 1

Example

Reports the error
<note>a\x01b</note>
Fixed
<note>a b</note>