Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Book Cover Beginning XML Programming
62968 times
Rated
Read 62,968 times

Contents

Related Categories

Beginning XML - Empy Elements

Empy Elements

Sometimes an element has no data. Recall our earlier example, where the middle element contained no name:

  <name nickname='Shiny John'>
    <first>John</first>
    <!--John lost his middle name in a fire-->
    <middle></middle>
    <last>Doe</last>
  </name>

In this case, you also have the option of writing this element using the special empty element syntax:

  <middle/>

This is the one case where a start-tag doesn't need a separate end-tag, because they are both combined together into this one tag. In all other cases, they do.

Recall from our discussion of element names that the only place we can have a space within the tag is before the closing ">". This rule is slightly different when it comes to empty elements. The "/" and ">" characters always have to be together, so you can create an empty element like this:

  <middle />

but not like these:

  <middle/ >
  <middle / >

Empty elements really don't buy you anything - except that they take less typing - so you can use them, or not, at your discretion. Keep in mind, however, that as far as XML is concerned <middle></middle> is exactly the same as <middle/>; for this reason, XML parsers will sometimes change your XML from one form to the other. You should never count on your empty elements being in one form or the other, but since they're syntactically exactly the same, it doesn't matter. (This is the reason that IE5 felt free to change our earlier <parody></parody> syntax to just <parody/>.

Interestingly, nobody in the XML community seems to mind the empty element syntax, even though it doesn't add anything to the language. This is especially interesting considering the passionate debates that have taken place on whether attributes are really necessary.

One place where empty elements are very often used is for elements that have no (or optional) PCDATA, but instead have all of their information stored in attributes. So if we rewrote our <name> example without child elements, instead of a start-tag and end-tag we would probably use an empty element, like this:

  <name first="John" middle="Fitzgerald Johansen" last="Doe"/>

Another common example is the case where just the element name is enough; for example, the HTML <BR> tag might be converted to an XML empty element, such as the XHTML <br/> tag. (XHTML is the latest "XML-compliant" version of HTML.)

Comments

  • Re: [1704] Beginning XML

    Posted by johnnie on 16 Dec 2006

    Hi there


    I firstly want to make it clear I am a total beginner when it comes to XHTML etc.
    I am trying to write a number of pages based on some templates and have problems with CSS rende...

  • Re: [1704] Beginning XML

    Posted by sreehari on 14 May 2006

    it is very good and useful thanks