XSLT self-closing tags issue

后端 未结 12 874
遥遥无期
遥遥无期 2020-12-08 20:19

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:

相关标签:
12条回答
  • 2020-12-08 20:52

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-08 20:53

    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"/>
    
    0 讨论(0)
  • 2020-12-08 20:53

    Don't try this at home:

    <xsl:when test="self::* and not(text())">
        <xsl:value-of select="concat('&lt;', name(), '&gt;', '&lt;/', name(), '&gt;')" disable-output-escaping="yes"/>
    </xsl:when>
    
    0 讨论(0)
  • 2020-12-08 20:55

    If you are using XmlWriter as your ouput stream, use HTMLTextWriter instead. XMLWriter will reformat your HTML output back to XML.

    0 讨论(0)
  • 2020-12-08 20:56

    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/

    0 讨论(0)
  • 2020-12-08 20:59

    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

    0 讨论(0)
提交回复
热议问题