How to add a newline (line break) in XML file?

newline (aka line break or end-of-lineEOL) is special character or character sequence that marks the end of a line of text. The exact codes used vary across operating systems:

LF:    Unix
CR:    Mac OS up to version 9
CR+LF: Windows, DOS

You can use 
 for line feed (LF) or 
 for carriage return (CR), and an XML parser will replace it with the respective character when handing off the parsed text to an application. These can be added manually, as you show in your example, but are particularly convenient when needing to add newlines programmatically within a string:

  • Common programming languages:
    • LF"
"
    • CR"
"
  • XSLT:
    • LF<xsl:text>&#xA;</xsl:text>
    • CR<xsl:text>&#xD;</xsl:text>

Or, if you want to see it in the XML immediately, simply put it in literally:

<?xml version="1.0" encoding="UTF-8" ?>
<item>
    <text>Address</text>
    <data>
        Sample
        Text 123
    </data>
</item>

Newline still not showing up?

Keep in mind that how an application interprets text, including newlines, is up to it. If you find that your newlines are being ignored, it might be that the application automatically runs together text separated by newlines.

HTML browsers, for example, will ignore newlines (and will normalize space within text such that multiple spaces are consolidated). To break lines in HTML,

  • use <br/>; or
  • wrap block in an element such as a div or p which by default causes a line break after the enclosed text, or in an element such as pre which by default typically will preserve whitespace and line breaks; or
  • use CSS styling such as white-space to control newline rendering.

XML application not cooperating?

If an XML application isn’t respecting your newlines, and working within the application’s processing model isn’t helping, another possible recourse is to use CDATA to tell the XML parser not to parse the text containing the newline.

<?xml version="1.0" encoding="UTF-8" ?>
<item>
    <text>Address</text>
    <data>
        <![CDATA[Sample
                 Text 123]]>
    </data>
</item>

or, if HTML markup is recognized downstream:

<?xml version="1.0" encoding="UTF-8" ?>
<item>
    <text>Address</text>
    <data>
        <![CDATA[Sample <br/>
                 Text 123]]>
    </data>
</item>

Whether this helps will depend upon application-defined semantics of one or more stages in the pipeline of XML processing that the XML passes through.

Bottom line

newline (aka line break or end-of-lineEOL) can be added much like any character in XML, but be mindful of

  • differing OS conventions
  • differing XML application semantics

Leave a Comment