Question

I am using C# 3.5. I have an XML string that I pass to XslCompiledTransform object. I then display the output in a WebBrowser. All is working great except that the XML elements contain extra spaces which I need to display in the WinForms HTML browser. I can't use any javascript in the html. Here is a sample XML element:

<myelement>Here is where           extra spaces need to be retained</myelement>

I tried replacing the string " " with "&nbsp;"but that made the xml that the XslCompiledTransform object used to transform invalid (the XML is invalid). Then I tried replacing " " with "&amp;nbsp" but then the text &amp;nbsp; appeared in my html instead of a space. How can I get the extra spaces to appear?

Was it helpful?

Solution

Add

xml:space="preserve"

to your xsl stylesheet or your input doc.

Here's a thorough guide to whitespace handling in XSLT.

EDIT:

To retain white space in the rendered HTML, use css style white-space:pre on the element in which you want to preserve white-space.

OTHER TIPS

&nbsp; is an entity in the XHTML DTD, whose actual value is the character &#xA0;.

Therefore, you need to replace every space with &#xA0;.

As simple as:

translate(., ' ', '&#xA;')

Here is a complete example:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" encoding="ascii"/>

 <xsl:template match="/*">
     <p>
       <xsl:value-of select="translate(., ' ', '&#xA0;')"/>
     </p>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<myelement>Here is where           extra spaces need to be retained</myelement>

the wanted, correct result is produced:

<p>Here&#160;is&#160;where&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;extra&#160;spaces&#160;need&#160;to&#160;be&#160;retained</p>

and it is displayed in the browser as:

Here is where           extra spaces need to be retained

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top