XML parsers reject certain characters outright, and the fix depends on which rule you broke. Most bad characters fall into three buckets: markup-significant characters that need entity references (<, &, and sometimes >), characters illegal in XML 1.0 no matter what you do (most C0 control codes), and characters that are legal but need the right encoding declared or a CDATA section for convenience. The short answer: escape the five predefined entities, strip or replace disallowed code points before serialization, declare your encoding correctly, and validate the output before sending it downstream. This guide walks through each case in a workable order with checks along the way.
The Three Character Classes You're Actually Dealing With
Before touching any code, separate the problem into three distinct categories, because the remedies don't overlap.
Markup-significant characters. Inside element content and attribute values, < starts a tag, and & starts an entity reference. > is technically legal in content except in the sequence ]]>, but escaping it is harmless and common. These characters are valid XML — they just need representation.
Characters forbidden by the XML 1.0 grammar. The Char production in XML 1.0 permits tab (U+0009), line feed (U+000A), carriage return (U+000D), and the ranges U+0020–U+D7FF, U+E000–U+FFFD, and U+10000–U+10FFFF. That means most C0 controls — U+0000 through U+0008, U+000B, U+000C, U+000E through U+001F — cannot appear in an XML 1.0 document at all. Neither can unpaired surrogates (U+D800–U+DFFF), and U+FFFE and U+FFFF are excluded. No entity, CDATA section, or encoding trick makes these legal in XML 1.0; they must be removed, replaced, or carried some other way. XML 1.1 relaxes this somewhat by allowing most controls as character references, but XML 1.0 remains the default and the version most parsers and schemas expect, so assume 1.0 unless you control both ends of the pipeline.
Legal characters that behave badly. These include characters that are legal but trip up naive handling: ]]> inside text (must be split), CR/LF pairs that get normalized by parsers, characters above U+007F that depend on a correct encoding declaration, and invisible characters like U+200B or U+FEFF that sneak in from copy-paste and confuse humans even when parsers accept them.
Sort your input by class first. Most "invalid character" errors are class two, and no amount of escaping fixes them.
Prerequisites Before You Change Any Data
A few things need to be in place before the fix is safe to apply:
1: Know your target XML version. Assume XML 1.0 unless you control both producer and consumer. If you're generating for a third party, 1.0 is the safe assumption. 2: Know the declared encoding. Your document should declare it in the XML declaration, e.g. , and the bytes on the wire must actually match. A declaration that says UTF-8 over Latin-1 bytes is a common source of "invalid character" errors that look like escaping problems but aren't. 3: Identify where the data enters. Is it user input, a database column, a CSV import, a scraped page, or a generated string? The interception point determines your fix. 4: Have a validation step ready. A parser in strict mode (or an XSD/DTD validation pass) is your success check. Without one, you're guessing.
With those settled, you can apply fixes in order from least destructive to most.
Step 1: Escape the Five Predefined Entities
XML defines exactly five named entities, and they cover the markup-significant characters:
| Character | Entity | When needed |
|---|---|---|
| & | & | Always, in content and attributes |
| < | < | Always, in content and attributes |
| > | > | In the sequence ]]>; otherwise optional |
| " | " | Inside double-quoted attribute values |
| ' | ' | Inside single-quoted attribute values |
The practical rule: escape & first, then <, then the quote appropriate to your attribute delimiter. If you escape < before &, you'll turn < into < and double-escape. This ordering bug is the single most common escaping mistake.
Consider the string Tom & Jerry <3. Correct content output is Tom & Jerry <3. A naive replace of < first, then &, yields Tom & Jerry <3, which a parser reads back as Tom & Jerry <3 — wrong at the consumer.
A worked check: feed your escaped output to a strict parser and compare the parsed text node to your original string. If they match byte-for-byte, escaping is correct. If the parser errors, you moved too fast — likely you have class-two characters still in the payload.
Step 2: Strip or Replace Characters Illegal in XML 1.0
Escaping doesn't help with forbidden code points. Your only options are removal, substitution, or a different transport. Walk the input string code point by code point (not byte by byte — this matters for multibyte encodings), and apply a policy:
Filter approach. Keep only code points that satisfy the XML 1.0 Char production. Everything else is dropped. This is lossless for valid data and lossy for invalid data, which is usually the right trade-off for logs and display fields.
Replace approach. Map each illegal code point to a visible placeholder like ? or a Unicode replacement character (U+FFFD), or to an application-specific escape like \x07 that your consumer understands. This preserves the fact that something was there.
Reject approach. Refuse the input and return an error to the caller. Appropriate when the data shouldn't have contained controls in the first place, and silently mangling it would hide a bug upstream.
A concrete example: a database column contains the text Hello\x00World because of a truncation bug. No amount of & escaping produces valid XML 1.0. You either drop U+0000 (yielding HelloWorld), replace it (yielding Hello\uFFFDWorld), or reject the record. Pick one policy per field and document it, because mixed policies cause subtle data loss.
Watch for unpaired surrogates too. A lone high surrogate from a truncated UTF-16 string is illegal and often produces a confusing parser error far from its origin.
Step 3: Get the Encoding Right
Encoding problems masquerade as invalid-character problems. Two failure modes dominate.
Declared encoding doesn't match actual bytes. If the XML declaration says encoding="UTF-8" but the file was written as ISO-8859-1, bytes above 0x7F decode into wrong code points or trigger errors. Check the actual bytes: a valid UTF-8 file with non-ASCII content should show multibyte sequences, and a Latin-1 file with a single high byte like 0xE9 (é) is invalid UTF-8. The fix is to either re-encode the file to match the declaration or correct the declaration to match the file — don't do both blindly.
No declaration and a legacy default. Without a declaration and without a BOM, XML defaults to UTF-8. If you're feeding Latin-1 and omitted the declaration, non-ASCII characters fail. Always declare explicitly when you control the producer.
A reproducible check: open the file in a hex viewer and confirm the byte pattern matches the declared encoding, then run it through a parser that validates encoding strictly. If the parser chokes on a byte you expected to be a multibyte sequence, the declaration is wrong.
Step 4: Use CDATA for Bulky Markup-Like Text
CDATA sections let you include text containing < and & without escaping, which is handy for embedded snippets, code, or HTML fragments inside XML:
Three limits matter. First, CDATA cannot contain the closing sequence ]]>, so text with that sequence must be split across two sections or escaped. Second, CDATA does not legalize forbidden control characters — a NUL byte inside CDATA is still invalid in XML 1.0. Third, some consumers strip or mishandle CDATA, so don't use it for interoperability-critical fields unless you know the consumer handles it.
Use CDATA as a readability convenience, not as a fix for class-two characters. It's not.
Step 5: Handle Attribute Values Separately
Attribute values follow the same five entities but with different normalization rules. A literal tab, LF, or CR inside an attribute is normalized to a space by parsers, so if you need to preserve whitespace, use character references: , , . Unescaped < in an attribute is a flat error, and & must always be escaped.
A common trap: building attributes by string concatenation without escaping the quotes that occur in user data. If your value contains a " and you wrap it in double quotes, the attribute terminates early and the parser reports unexpected characters. Either escape the quote or use the other delimiter consistently.
Step 6: Use Character References for Precision
Numeric character references — &#NN; for decimal and &#xNN; for hex — work for any legal character. They're the tool of choice when your source environment can't handle raw non-ASCII (say, an ASCII-only channel) but the target is valid XML. é and é both represent é.
They cannot rescue class-two characters in XML 1.0: � is invalid because the code point itself is illegal. In XML 1.1, most controls become representable as character references, but the parser and your consumer must both agree to 1.1, which is rare in practice.
When generating references, compute from the code point, not from a byte. A multibyte UTF-8 sequence for a single character yields a single reference to that character's code point.
Step 7: Serialize with a Real XML Library
Hand-rolled string concatenation is where most invalid-character bugs are born. Every mainstream language ships a serializer that handles escaping, encoding, and attribute rules for you: .NET's XmlWriter, Java's DocumentBuilder/Transformer, Python's xml.etree.ElementTree (tostring) or lxml, JavaScript's XMLSerializer in the DOM, PHP's DOMDocument.
The gain isn't just convenience. Libraries apply the correct escaping order, enforce the grammar, and reject illegal characters at write time instead of producing a document that fails downstream. If you must pre-process, do it before handing the string to the serializer, and let the serializer own the escaping.
A check that catches most library misuse: round-trip your data — serialize, parse, compare to the original text nodes. Mismatches reveal double-escaping or lost characters. If the library throws on write, the payload contains a class-two character; go back to step two.
Step 8: Validate and Verify
Validation is the stop-and-check point. Run the serialized document through a strict parser with DTD or XSD validation if your consumer enforces one. Ambiguities in well-formedness often surface only here.
Success looks like: the parser accepts the document, the parsed text nodes equal your intended values, and the consumer's own validation passes. Failure modes and their likely causes:
"Invalid character" at a specific position. Class-two code point at or near that byte offset. Inspect the raw bytes, not the rendered text. "Entity not defined" or "malformed entity reference." Missing semicolon, double-escaped &, or a named entity that isn't one of the five predefined ones. Use numeric references rather than inventing names. Garbled non-ASCII characters after parsing. Encoding declaration mismatch. Compare bytes to the declaration. "Content is not allowed in prolog" or unexpected markup. A raw < in content or an unclosed construct, often from unescaped user data.
If validation fails after the escape-and-filter steps, check whether your consumer expects a specific schema or namespace — those produce errors that look character-related but are structural.
Where This Breaks Down: Limits and Edge Cases
XML 1.0's hard ceiling. There's no clean way to carry binary data or arbitrary control codes inside XML 1.0 text nodes. The standard workaround is base64 encoding the payload, which is lossless and legal. Use it for binary fields; don't contort character escapes to approximate it.
Encoding round-trips. Some pipelines transcode through intermediaries — an ASCII-only channel, a legacy database — that mangle characters above U+007F or drop them silently. Test with real non-ASCII data (CJK, emoji, combining marks), not just é, because emoji live above U+FFFF and require surrogate pairs in UTF-16 and four bytes in UTF-8. A pipeline that handles é may still corrupt a rocket emoji.
Whitespace normalization. Parsers normalize CRLF and CR to LF in content, and attribute whitespace to spaces. If exact byte preservation matters, use character references and document the expectation, or accept normalized output.
BOM handling. A byte-order mark at the start of a UTF-8 document is tolerated by most parsers but breaks some naive consumers and string comparisons. Avoid emitting it unless your target requires it.
Mixed versions. Features differ between XML 1.0 and 1.1, so a document valid under one may fail under the other. Declare the version and test against the version your consumer uses.
Schema-level restrictions. Your DTD or XSD may further restrict allowed characters via patterns and enumerations. A document can be well-formed and valid XML 1.0 yet fail your schema — that's a validation fix, not an escaping one.
Troubleshooting Order That Saves Time
When a parser reports an invalid character, resist the urge to start adding & everywhere. Work through reversible checks first:
1: Locate the byte offset from the error and inspect the raw bytes there. Is it a control code (class two), or a markup character that needed escaping (class one)? 2: Confirm the encoding declaration matches the bytes. This is reversible and common. 3: Check for double-escaping. Search for < or similar sequences in the output. 4: Isolate the offending input. Reproduce with the smallest payload that fails, which usually makes the class obvious. 5: Apply the class-specific fix — escape, filter, or re-encode as determined. 6: Stop and escalate when the payload contains binary or control data that the XML contract genuinely can't represent. At that point the right fix is a design change: base64, a separate transport, or a schema amendment — not a more creative escaping scheme.
That last point is the one worth internalizing. XML's character rules aren't a nuisance to route around; they're a boundary. Escaping handles representation, filtering handles illegal data, encoding handles transport. When none of those fit, the data model is the problem, and a professional review of the interface is cheaper than a pile of workarounds.