Not for the first time I’ve been caught out when trying to do simple XSLT to pick information out of XML files. Hopefully this is the last. I’m blogging this so I can refer to it again later. Hopefully it will be useful to you too.

If your XSLT is behaving strangely, there are two golden rules to remember.

  1. There are some default rules that control how items are processed if they don't match any rules (basically applying templates to nested elements automatically, and copying text() nodes to the output verbatim). If you're deliberately trying to filter some content out of the file then you'll want to override these.
  2. If your XSLT isn't matching any elements at all, make sure the XML you're trying to parse hasn't got a top-level namespace defined. If it does, you'll have to match it in the XSLT as well or use it in front of every XML element you want to match.

Example

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:apply-templates />
    </xsl:template>
    <xsl:template match="text()" />

    <!-- Now pick out the elements you are interested in -->
</xsl:stylesheet>

Bearing these two simple rules in mind could help to prevent a lot of head-scratching when dealing with XSLT that appears to be behaving against all logic.