Beginning XML

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.)

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The generation of random numbers is too important to be left to chance.” - Robert R. Coveyou