Say I have a very simple XML with an empty tag 'B':
<Root>
<A>foo</A>
<B></B>
<C>bar</C>
</Root>
I'm currently using XSLT to remove a few tags, like 'C' for example:
<?xml version="1.0" ?>
<xsl:stylesheet version="2.0" xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="utf-8" omit-xml-declaration="yes" />
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="C" />
</xsl:stylesheet>
So far OK, but the problem is I end up having an output like this:
<Root>
<A>foo</A>
<B/>
</Root>
when I actually really want:
<Root>
<A>foo</A>
<B></B>
</Root>
Is there a way to prevent 'B' from collapsing?
Thanks.
This works fine with C#'s
XslCompiledTransform
class with .Net 2.0, but may very well fail almost anywhere else. Do not use unless you are programmatically doing the transofrm yourself; it is not portable at all.This has been a long time issue and I finally made it work with a simple solution. Add <xsl:text/> if you have a space character. I added a space in my helper class. <xsl:choose> <xsl:when test="$textAreaValue=' '"> <xsl:text/> </xsl:when> <xsl:otherwise> <xsl:value-of select="$textAreaValue"/> </xsl:otherwise> </xsl:choose>
It is up to the XSLT engine to decide how the XML tag is rendered, because a parser should see no difference between the two variations. However, when outputting HTML this is a common problem (for
<textarea>
and<script>
tags for example.) The simplest (but ugly) solution is to add a single whitespace inside the tag (this does change the meaning of the tag slightly though.)No. The 2 are syntactically identical, so you shouldn't have to worry
Ok, so here what worked for me:
There should also be another method (XSLT2 only?): "xhtml" (see another thread). This keeps your tags from collapsing and does not remove closing tags from elements like <meta>.