Why XML Parsers Convert CRLF to LF
An XML parser automatically converts carriage return and line feed (CRLF) combinations into a single line feed (LF) to maintain consistent cross-platform document handling. This behavior, known as end-of-line normalization, is mandated by the W3C XML specification so that identical XML documents produce the same parsed data regardless of the operating system used to create, edit, or process them.
The Operating System Discrepancy
Different operating systems historically adopted different byte sequences to denote the end of a line of text:
- Windows and DOS: Use a two-character sequence
composed of Carriage Return followed by Line Feed (
\r\nor hex0x0D 0x0A). - Unix, Linux, and modern macOS: Use a single Line
Feed character (
\nor hex0x0A). - Classic Mac OS (pre-OS X): Used a single Carriage
Return character (
\ror hex0x0D).
If an XML document were passed across different operating systems without normalization, downstream applications would receive different character sequences for the exact same file. This would lead to discrepancies in string lengths, regular expression matching, and data integrity checks.
W3C End-of-Line Handling Specification
To eliminate cross-platform anomalies, Section 2.11 (“End-of-Line Handling”) of the W3C XML 1.0 specification requires all conforming XML parsers to normalize line endings before passing character data to the application.
The parser applies these translation rules on all parsed entities:
- Any two-character sequence of
#xD #xA(Carriage Return + Line Feed) is converted into a single#xA(Line Feed). - Any standalone
#xD(Carriage Return) that is not immediately followed by#xAis converted into a single#xA.
In XML 1.1, this rule was further expanded to include other Unicode
line-ending characters, such as Next Line (#x85) and Line
Separator (#x2028), converting them into #xA
as well.
Benefits of Line Break Normalization
- Simplified Application Logic: Developers processing
XML do not need to write defensive code to check for
\r\n,\r, or\n. They can consistently expect\n. - Deterministic Hashing and Signatures: Canonical XML and XML Digital Signatures (XML-DSig) require byte-for-byte predictability. Converting line endings into a unified format ensures cryptographic hashes match across different systems.
- Seamless Transport: XML files transmitted via protocols that might alter line breaks (like certain FTP modes or email systems) retain identical parsed semantics.
How to Preserve Carriage Returns
If an application strictly requires a literal Carriage Return
(#xD) in its data, the character must be written as a
numeric character reference: or

.
Because XML processors resolve character references after the
end-of-line normalization step takes place, the parser will preserve the
literal #xD character and deliver it to the application
intact.