Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it "bad practice" to be sensitive to linebreaks in XML documents?

I'm generating some XML documents and when it comes to the address part I have fragments that look like this:

<Address>15 Sample St
Example Bay
Some Country</Address>

The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags.

This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?

<Address><Line>15 Sample St</Line>
<Line>Example Bay</Line>
<Line>Some Country</Line></Address>

Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..

like image 765
pauldoo Avatar asked Aug 10 '08 18:08

pauldoo


1 Answers

It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed.

The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform.

Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks.

If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.)

Some suggested reading

  • An article from XML.com says the following:

XML applications often seem to take a cavalier attitude toward whitespace because the rules about the places in an XML document where whitespace doesn't matter sometimes give these applications free rein to add or remove whitespace in certain places.

  • A collection of XSL-list posts regarding whitespace.
like image 129
James Sulak Avatar answered Sep 18 '22 17:09

James Sulak