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:

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:

  1. Any two-character sequence of #xD #xA (Carriage Return + Line Feed) is converted into a single #xA (Line Feed).
  2. Any standalone #xD (Carriage Return) that is not immediately followed by #xA is 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

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.