I have done a good amount of experimentation with XSLT and the XMLTransform() method in ColdFusion; but, up until now, that's all pretty much been with strict XML documents. Over the weekend, I was thinking of re-architecting some parts of my blog and I thought XSLT might just be the best approach. But then it occurred to me that I didn't know if XSLT would play nicely with XHTML-style data. To be honest, I am not even sure if XHTML validates as XML. For the most part, the parallel nature of the two types of document are obvious; the one uncertainty for me is the mixture of text nodes and elements within a single parent.
To see how XSLT and XHTML work together, I set up a simple demo that creates a copy of a chunk of XHTML data by copying each node within it separately:
<!--- Define XHTML style data. ---> <cfsavecontent variable="strData"> <p class="content"> This is some text with some other formatted text <strong>contained within in</strong>. While this is valid XHTML, I am wondering how it will hold up when put through <em>XSLT</em> node copying. <img src="about:blank" /> Embedded image. </p> </cfsavecontent> <!--- Define the XSLT. ---> <cfsavecontent variable="strXSLT"> <!--- Document type declaration. ---> <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!--- Match all generic nodes. ---> <xsl:template match="*"> <!--- Copy this node (non-deep copy). ---> <xsl:copy> <!--- Make sure that all attributes are copied over for the current node. ---> <xsl:copy-of select="@*" /> <!--- Apply templates to all of it's child nodes (so that they can be copied). ---> <xsl:apply-templates /> </xsl:copy> </xsl:template> </xsl:transform> </cfsavecontent> <!--- Transfor the XHTML. Let's see if this creates an accurate copy of the XHTML. ---> #HtmlEditFormat( XMLTransform( Trim( strData ), Trim( strXSLT ) ) )#
As you can see, my XSLT is simply copying each node and then recursively calling Copy on each of its child nodes. When we run this code, we get the following output:
<?xml version="1.0" encoding="UTF-8"?> <p class="content"> This is some text with some other formatted text <strong>contained within in</strong>. While this is valid XHTML, I am wondering how it will hold up when put through <em>XSLT</em> node copying. <img src="about:blank"/> Embedded image. </p>
With the exception of the added XML DocType, I am happy to see that ColdFusion's XMLTransform() and my XSLT work quite well with XHTML style data. This verifies that XHTML does indeed validate as XML. Let's see if I can start putting this new found compatibility insight into use.
Want to use code from this post? Check out the license.