Opening and closing tags. Getting around XML rules of XSLT

Working with XSLT in SharePoint can make you come up with some ‘creative’ solutions to a problem.

When using the Content Query WebPart (CQWP), the XML data from a SharePoint list is passed to the CQWP XSLT template node by node. So if you want to render the data in a HTML table, you need to render a <table> tag before the first node with of data and close with a </table> tag after the last node with data. Unfortunately, XSLT doesn’t accept single opening or closing tags. Everything in XSLT must be opened and closed. An opening tag without a closing tag or vice versa is not allowed.

So you need to get creative…

You can put the single opening and closing tags in XSL variables. This way, the XSLT engine won’t complain about any ‘malformed’ HTML. But then you also need to know when the variable should contain a HTML tag and when it should be empty. You can test for this situation by counting the preceding siblings (where 0 = first XML node) and following siblings (where 0 = last XML node).

<xsl:variable name="openTable">
  <xsl:if test="count(preceding-sibling::*) = 0">
<xsl:variable name="closeTable">
  <xsl:if test="count(following-sibling::*) = 0">

Now that we have defined the variables, we must place the variables in the XSLT template to render the HTML, contained in the CDATA tags. This is a simple XSL statement, but you shouldn’t forget to disable the output escaping:

And of course, the reason this works is that the variable containing the CDATA with the opening or closing tag only has data when the XSLT template is called with the first or last node.

Ernst Wolthaus

4 thoughts on “Opening and closing tags. Getting around XML rules of XSLT

  1. Pingback: Pro-tip: Outputting ‘Invalid’ XML with XSLT – Henry Chong

Leave a Reply

Your email address will not be published. Required fields are marked *