[xsl] RE: Question About Translate Function

Subject: [xsl] RE: Question About Translate Function
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Sun, 27 Nov 2005 22:35:05 -0000
>  Using the XSLT translate function, is there a way to change
>  &lt; to < and &gt; to >. I have an XML document, saved out
>  of Microsoft InfoPath, which changes the XML tags pasted into
>  a text box into a text string of (for example)
> 
>  &lt;myXmlElementName&gt;myXmlElementText&lt;/myXmlElementName&gt;
>  instead of <myXmlElementName>myXmlElementText</myXmlElementName>

The character that appears as &lt; in the lexical source XML is actually a
"<" character, and is seen as such by the XSLT processor. If you want to
translate this into something else, the second argument of translate should
be a string containing the single character "<", and the way you write such
a string in XSLT (or in any other XML document), is "&lt;".

The problem comes with your output. I don't think you want the result tree
to contain a "<" character, I think you want it to contain an element node
with the name myXMLElementName, so that when the result tree is serialized
back to lexical XML it will come out as
<myXMLElementName>...</myElementName>. You can't use the translate()
function to create an element node, or to create lexical markup.

The right design here is to parse the input string into an XML tree and then
copy the XML tree to the output. If you're using Saxon, that's <xsl:copy-of
select="saxon:parse($input)"/>. Another solution that will work on many XSLT
processors (depending on the environment) is to use disable-output-escaping:

<xsl:value-of select="$input" disable-output-escaping="yes"/>

However, it's hard to come up with a completely portable solution, basically
because your source XML is poorly designed: "<" and ">" should be escaped
when they represent ordinary characters, but should not be escaped when (as
here) they represent markup.

Michael Kay
http://www.saxonica.com/

> 
>  I'm using Apache Cocoon Version 2.0.3.
>  This is the translate function that I'm using:
>  <xsl:value-of select="translate(//myXmlElementName, '<', '<')" />
>  <xsl:value-of select="translate(//myXmlElementName, '>', '>')" />
> 
>  This is part of the error message that Cocoon generates:
> 
>  The value of attribute "select" must not contain the '<' character.
>   org.apache.cocoon.ProcessingException: Exception in 
> creating Transform 
> Handler:
>   org.xml.sax.: SAXParseException: The value of attribute 
> "select" must 
> not contain the "<" character.
> 
>  Any ideas?
> 
>  Thanks,
> 
>  Greg

Current Thread