Using xsl:if doesn't include closing tag

2019-05-31 16:41发布

问题:

Trying to use the following code to insert a google ad inside of a blog roll

<xsl:if test="position() = 3">
    <object data="/frontpage_blogroll_center_top_728x90" 
            width="735" 
            height="95"  ></object>
</xsl:if>  

For some reason the closing tag </object> doesn't get rendered in the HTML and causes error. Is there anyway to resolve this?

回答1:

There is no difference (except lexical) in XML between:

<object></object>

and

<object/>

These represent exactly the same XML element, and different XSLT processors are free whichever of the two representations above they choose.

If the long form of the element is really needed in HTML, this can be achieved by either:

  • Using <xsl:output method="xhtml"/> . The xhtml method is only available in XSLT 2.0.

  • Using <xsl:output method="html"/> . The result of the XSLT transformation will be an HTML document (not XML).

  • Using a trick, like:

    <object data="/frontpage_blogroll_center_top_728x90" width="735" height="95"  >
      <xsl:value-of select="$vsomeVar"/>
    </object>
    

where $vsomeVar has no value and will not cause anything to be output, but will trick the XSLT processor into thinking something was output and thus outputting the long form of the element.



回答2:

Use html output method.

This stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>
    <xsl:template match="/">
        <xsl:if test="true()">
            <object data="/frontpage_blogroll_center_top_728x90"
                    width="735"
                    height="95"  ></object>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Output:

<object height="95" 
        width="735" 
        data="/frontpage_blogroll_center_top_728x90"></object>

Tested with MSXSL, Xalan, Oracle, Saxon, Altova, XQSharp.