I was asking myself the other day, why does XML use explicit closing tags?

What I mean is, like:

  <person>
    <name>Phil</name>
    <gender>Male</gender>
    <occupation>Rails Developer</occupation>
  </person>

Normal enough. We’re used to this, it’s just the way it works.

Except that it’s not really necessary; other than for human readability (which may be a good enough reason), there’s no technical reason a tag should need to be closed by name.

In other words, we could decide that we could write:

  <person>
    <name>Phil</>
    <gender>Male</>
    <occupation>Rails Developer</>
  </>

Now, that’s not valid XML, but I don’t see any reason why it couldn’t be adopted. The reason it would work is that in XML, overlapping tags is illegal. Therefore, every closing tag should automatically be assumed to be closing the most recently opened tag.

For example, this is illegal:

  <strong><p>You shouldn't do <em>this</strong></p></em>

Ecch. However, if you were allowed to use </> as a generic closing tag, you could write the above as:

  <strong><p>You might do <em>this</></></>

Notwithstanding that it’s illegal to next a block element inside an inline element, each closing tag would be assumed to be closing the most recently opened tag, so they would all match. Let’s switch <strong> and <p> to make it valid:

<p> <strong> Like <em> this </> </> </>

Now, I’m not actually seriously proposing changing the XML standard just because it would work. Having to close tags which match the element name, i.e. <block></block> certainly aids readability. In fact, I find that with generic tags, like <div>, I often follow the the ending </div> tag with a comment, such as <!-- #the_id_of_the_div_block -->, just so it’s easy to figure out what’s going on when you read the code a year from now. So maybe ending xml elements with meaningful end tags is just a Good Idea, regardless of whether or not generic closing tags would “work”.

I just thought it was interesting that they would work, and I wonder if this has ever come up. Anyone know?

2 Responses to “Why Does XML Use Explicit Closing Tags For Elements?”

  1. mrben Says:

    And suddenly whitespace as delimiters doesn't seem so stupid ;)
  2. Phil Crissman Says:

    Well. It was just a thought. ;P

Sorry, comments are closed for this article.