I am using xslt to transform an xml file to html. The .net xslt engine keeps serving me self-closing tags for empty tags.
Example:
The easy way I found was creating a new XmlTextWriter class to override the method WriteEndElement, forcing the non-closing tag and pass on the serialization process as parameter.
public class MyXmlTextWriter : XmlTextWriter
{
public MyXmlTextWriter(Stream stream) : base(stream, Encoding.UTF8)
{ }
public MyXmlTextWriter(TextWriter stream) : base(stream)
{ }
public override void WriteEndElement()
{
base.WriteFullEndElement();
}
}
Change your xsl:output
method to be html
(instead of xml
).
Or add it if you haven't already got the element
<xsl:output method="html"/>
Don't try this at home:
<xsl:when test="self::* and not(text())">
<xsl:value-of select="concat('<', name(), '>', '</', name(), '>')" disable-output-escaping="yes"/>
</xsl:when>
If you are using XmlWriter as your ouput stream, use HTMLTextWriter instead. XMLWriter will reformat your HTML output back to XML.
I use the following whenever I wish to prevent an element from self-closing:
<xsl:value-of select="''" />
This fools the rendering engine into believe there is content inside the element, and therefore prevents self-closure.
It's a bit of an ugly fix so I recommend containing it in a descriptive template and calling that each time instead:
<xsl:template name="PreventSelfClosure">
<xsl:value-of select="''" />
</xsl:template>
<div class="test">
<xsl:call-template name="PreventSelfClosure"/>
</div>
This will then render the following:
<div class="test"></div>
http://curtistimson.co.uk/post/xslt/how-to-prevent-self-closing-elements-in-xslt/
A workaround can be to insert a comment element to force generation of non self closing:
<script type="text/javascript" src="nowhere.js">
<xsl:comment></xsl:comment>
</script>
It is not a pretty soloution, but it works :-)
/Sten