XML creation: Part 7

In this guide, I'll be creating an XML file to store the Playstation games I own, and ultimately make the XML file 'pretty' for Web browsers. I've done this in the past, with my vehicle gas XML document.

In part seven I'll be expanding upon our XSLT to remove elements that are empty, and change the sort order, for our existing XML file.

Last time ...

Up until now we've decided what we want to store, and how we want to store it, in an XML file.

Then, in part three, we actually added some of the data we want to store.

In part four, we made the XML file valid by associating a DTD.

In part five we started making the XML document pretty, in modern browsers, by using CSS. In part six we were able to mimic this look using an XSLT file instead.

Overview

However, while we've been able to mimic the CSS output, what we really want to do is make it better.

To do this we'll want to hide elements that are empty, such as when a game hasn't been sold, as well as change the sort order from according to how they're entered in the XML file, to one based upon game title.

Using XSLT to sort the content

Adding a new sort order is super easy. All we need to do is add an xsl:sort immediately after our xsl:for-each.

So, find the following line.

<xsl:for-each select="game">

Now add this line immediately after it.

<xsl:sort select="title" data-type="text" />

If we wanted to add another sort, we could simply add another line, like the above, after this addition. Pretty simple, huh?

Using XSLT to hide empty elements

Now that we're sorting, we'll attempt to hide any elements which are empty, which in this case means the sell data, and the notes.

First, we'll use conditional logic to hide the sell data, depending upon whether own is equal to no or yes.

<xsl:if test="own = 'no'">
   <div style="margin-left:1em;">
      Sold <xsl:value-of select="sell/date" />
      for $<xsl:value-of select="sell/price" />
   </div>
</xsl:if>

As you can see, we've added two new lines. On the first line we've added an if statement. If the value of own is 'no', we'll display the sell data. Otherwise, we won't.

For notes, we can do something similar.

<xsl:if test="notes != ''">
   <div style="font-style:italic;margin-left:1em;">
      Notes: <xsl:value-of select="notes" />
   </div>
</xsl:if> 

Here we're checking to see if notes is empty, and if it is not, we're displaying the notes.

Where we're at now

Now we've got an XML document, with XSLT, that displays more like we'd expect.

Next time ...

Even though I was going to go over it here, I decided to hold off adding additional games until the next part. In that part I'll be adding some additional games, from the Playstation 2, and changing the display so that we can easily separate them out.