Sams Teach Yourself XML in 21 Days

Sams Teach Yourself XML in 21 Days

By Steven Holzner

Creating XML Comments

You can use comments to include explanatory and descriptive notes in a document. Comments are ignored by XML parsers and may appear anywhere in a document outside other XML markup. XML comments look very much like HTML comments. As in HTML, you start a comment with <!-- and end it with -->. Here's an example:

<?xml version="1.0" encoding="UTF-8"?>
    <!--Here comes the document element...-->
<document>
    <!--The next element contains a heading.-->
    <heading>
        Hello From XML
    </heading>
    <!--The next element contains the actual message.-->
    <message>
        This is an XML document!
    </message>
</document>

The text inside a comment is ignored by XML processors (unless, with some XML processors, that text includes markup, which is sometimes mistakenly treated as markup).

You're only supposed to use comments outside markup—for example, this is not legal:

<?xml version="1.0" encoding="UTF-8"?>
<document >
    <heading <!--This is the heading element-->>
        Hello From XML
    </heading>
    <message>
        This is an XML document!
    </message>
</document>

You should not use the character sequence -- in the text of a comment, because when some XML processors see that sequence, they assume the comment is ended. For example, don't do this:

<?xml version="1.0" encoding="UTF-8"?>
<document >
    <heading>
        Hello From XML
    </heading>
    <!--This is our--friendly--message element-->
    <message>
        This is an XML document!
    </message>
</document>

In particular, the XML 1.0 specification says that comments cannot end with the sequence --->. Also, comments cannot come before an XML declaration (nothing can). So this usage is not legal:


   <!--This document contains a message.-->
<?xml version="1.0" encoding="UTF-8"?>
<document >
    <heading>
        Hello From XML
    </heading>
    <message>
        This is an XML document!
    </message>
</document>

It's also worth knowing that in most XML processors, you can use comments to exclude sections of a document from being treated as markup. For example, here's how you might remove the <heading> element as far as an XML processor is concerned:

<?xml version="1.0" encoding="UTF-8"?>
<document >
<!--

       <heading>

           Hello From XML

       </heading>

   -->
    <message>
        This is an XML document!
    </message>
</document>

As far as most XML processors are concerned, here's what the content of this XML document looks like:

<?xml version="1.0" encoding="UTF-8"?>
<document >
    <message>
        This is an XML document!
    </message>
</document>

Share ThisShare This

Informit Network