Spaces in XML element to show in HTML control
-
24-06-2021 - |
문제
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 " "
but that made the xml that the XslCompiledTransform object used to transform invalid (the XML is invalid). Then I tried replacing " " with "&nbsp"
but then the text &nbsp;
appeared in my html instead of a space. How can I get the extra spaces to appear?
해결책
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.
다른 팁
is an entity in the XHTML DTD, whose actual value is the character  
.
Therefore, you need to replace every space with  
.
As simple as:
translate(., ' ', '
')
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(., ' ', ' ')"/>
</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 is where           extra spaces need to be retained</p>
and it is displayed in the browser as:
Here is where extra spaces need to be retained