XML technologies / XML / Perl & XML / Introduction to XML / Indentation
(Excerpt from "Perl & XML" by Erik T. Ray & Jason McIntosh)
You have probably noticed in the previous examples that we indent elements with extra whitespace to make documents easier for people to read. There are good reasons for this, since XML documents are often edited with a simple text editor or similar tool. Sometimes, however, this indentation introduces whitespace that is unwanted during actual processing. XML’s philosophy is “no assumptions or ambiguities”. It may therefore seem that you have to live with this whitespace.
One possible solution is to make the XML processor a little smarter. Many parsers can suppress whitespace if they believe it serves only for indentation. (Note: A parser is a specialized XML handler that preprocesses a document for the rest of the program. Parsers vary in how “intelligently” they interpret XML. We will return to this in XML basics: reading and writing.) For this purpose, the parser uses the DTD. If it finds whitespace where no text is declared, it assumes it can omit it. You can also adapt a parser to a specific markup language and define special whitespace handling for certain elements.
Finally, XML itself also provides a way to require whitespace preservation. The attribute xml:space can be used on any individual element as an instruction to the parser. (Note: We know it is a reserved attribute because it begins with the prefix “xml”. The XML standard reserves element and attribute names with this prefix for special uses.) For example:
<address-label xml:space='preserve'>Haribostr. 246 70565 Stuttgart Deutschland</address-label>The attribute value “preserve” means that whitespace in this element must always be preserved. The value “default” (the default setting), on the other hand, allows the processor to ignore whitespace.
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from the book "Perl & XML" is subject to the same conditions as the printed edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de
back to top