Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT special characters

Tags:

xml

xslt

In the following XSL transformation how do I output the '<' and '>' symbol?

Input XML:

<TestResult bugnumber="3214" testname="display.methods::close->test_ManyInvoke" errortype="Failure"><ErrorMessage><![CDATA[calling close() method failed - expected:<2>]]></ErrorMessage>

XSLT:

<xsl:template match="TestResult">
  <xsl:variable name="errorMessage">
   <xsl:value-of select="ErrorMessage" disable-output-escaping="yes"/>
  </xsl:variable>
  <Test name='{@testname}'>
   <TestResult>
    <Passed>false</Passed>
    <State>failure</State>
    <Metadata>
     <Entry name='bugnumber' value='{@bugnumber}' />
    </Metadata>
    <TestOutput>
     <Metadata>
      <Entry name='ErrorMessage' value='{$errorMessage}' />
     </Metadata>
    </TestOutput>
   </TestResult>
  </Test>
 </xsl:template>

Output XML:

<Test name="display.methods::close-&gttest_ManyInvoke"> 
 <TestResult>
  <Passed>false</Passed>
  <State>failure</State>
  <Metadata>
   <Entry name="bugnumber" value="3214"/>
  </Metadata>
  <TestOutput>
   <Metadata>
    <Entry name="ErrorMessage" value="calling close() method failed - expected:&lt;2&gt;"/>
   </Metadata>
  </TestOutput>
 </TestResult>
</Test>
like image 448
Apurv Avatar asked May 28 '10 00:05

Apurv


2 Answers

Short answer: You can't.

Long answer: The value of attributes cannot contain a few special characters, such as '<', '>' and '&'.

If present, they are escaped as: '&lt;', '&gt;' and '&amp;' .

These characters can be produced if the output method is 'text', which is not your case.

Text that looks like these characters when displayed in a browser can also be produced: use: '&lt;', '&gt;' and '&amp;'.

Finally, you can produce these characters as part of a text node using CDATA section. The following example illustrates this:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
 <xsl:output cdata-section-elements="t"
  omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <t> &lt; &amp; &gt;</t>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used), the result is:

<t><![CDATA[ < & >]]></t>
like image 51
Dimitre Novatchev Avatar answered Sep 28 '22 05:09

Dimitre Novatchev


This is a really old question, and the other commenters are probably right to question why you need this, but if you just want to know how to add a < or > into your output here's how you do it.

<xsl:value-of disable-output-escaping="yes" select="string('&lt;')"/>

More info at the MSDN site.

like image 20
GMK Avatar answered Sep 28 '22 05:09

GMK