Re: [xsl] <textarea>, HTML and CDATA

Subject: Re: [xsl] <textarea>, HTML and CDATA
From: Mike Brown <mike@xxxxxxxx>
Date: Mon, 3 Feb 2003 20:02:02 -0700 (MST)
Anode wrote:
> XML:
> <codebox>
> <strong>Hello, World!</strong>
> </codebox>
>
> Output XHTML
> <form>
> <textarea rows = "5" columns = "50">
> <strong>Hello, World!</strong>
> </textarea>
> </form>
> 
> The purpose would be to provide a textarea with code my visitors can cut and
> paste.

Well, creating the result that you're asking for is easy...

<xsl:template match="codebox">
  <form>
    <textarea rows="5" columns="50">
      <xsl:copy-of select="."/>
    </textarea>
  </form>
</xsl:template>

... but it is also incorrect. You are somewhat confused about what happens to
"work" in these lenient tag-soup readers we call HTML user agents, versus what 
is actually correct HTML and XHTML syntax. This is what you really want:

<form>
  <textarea rows="5" columns="50">
    &lt;strong&gt;Hello, world!&lt;/strong&gt;
  </textarea>
</form>

(try it in a web browser... it works, more reliably, even...)

Now if your XML must remain as it is in your example, then it is difficult to
get this output, because in the XPath/XSLT data model you don't have the XML
as a string; rather it has been parsed into a tree of nodes, so the original
tags and other artifacts of linear serialization are long gone, and there are
no standard facilities for "demoting" it to mere character data. Some
processors do offer extension functions to convert a node-set to a string, and
it is possible to do it (slowly) via templates like those at
http://www.xmlportfolio.com/xml-to-string/, but if the data was never intended
to be used as anything but character data in the first place, then it
shouldn't have been given elevated status in the XML source in the first
place. That is, if the XML were either of these (they are 100% equivalent),

  <codebox>&lt;strong&gt;Hello, World!&lt;/strong&gt;</codebox>

  <codebox><![CDATA[<strong>Hello, World!</strong>]]></codebox>

then 

  <xsl:template match="codebox">
    <form>
      <textarea rows="5" columns="50">
        <xsl:value-of select="."/>
      </textarea>
    </form>
  </xsl:template>

would suffice.

Mike

-- 
  Mike J. Brown   |  http://skew.org/~mike/resume/
  Denver, CO, USA |  http://skew.org/xml/

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread