XSLT self-closing tags issue

2019-01-17 10:49发布

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:

<div class="test"></div> 

becomes

<div class="test" />

The former is valid html, while the latter is illegal html and renders badly. My question is : How do I tell the xslt engine (XslCompiledTransform) to not use self-closing tags.

If it's not possible, how can I tell my browser (IE6+ in this case) to interpret self-closing tags correctly.

11条回答
欢心
2楼-- · 2019-01-17 11:14

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

查看更多
三岁会撩人
3楼-- · 2019-01-17 11:15

I used to put an <xsl:text> element inside, like:

<script type="text/javascript" src="/scripts/jquery.js"><xsl:text> </xsl:text></script>
查看更多
欢心
4楼-- · 2019-01-17 11:17

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/

查看更多
来,给爷笑一个
5楼-- · 2019-01-17 11:19

Just experienced the same issue with PHP 5's XSL, with output/@method=html. Seems that assigning an empty value attribute will cause elements to be output as invalid non-self-closing, non-closed tags:

<input type="text" name="foo" value="{my-empty-value}" />

results in:

<input type="text" name="foo" value="">

One possible solution is to conditionally add the attribute:

<xsl:if test="string-length(my-empty-value) > 0">
    <xsl:attribute name="value">
        <xsl:value-of select="my-empty-value" />
    </xsl:attribute>
</xsl:if>

resulting in:

<input type="text" name="foo" />
查看更多
beautiful°
6楼-- · 2019-01-17 11:20

For me it was a problem in the script tag. I solved it by filling it with a semicolon (;)

<script type="text/javascript" src="somewhere.js">;</script>
查看更多
登录 后发表回答