How to preserve Empty XML Tags after XSLT - preven

2019-01-26 05:55发布

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.

标签: java xml xslt
11条回答
Bombasti
2楼-- · 2019-01-26 06:18
<xsl:text disable-output-escaping="yes">
<![CDATA[<div></div>]]>
</xsl:text>

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.

查看更多
Viruses.
3楼-- · 2019-01-26 06:28

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>

查看更多
爷的心禁止访问
4楼-- · 2019-01-26 06:33

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.)

查看更多
趁早两清
5楼-- · 2019-01-26 06:33

No. The 2 are syntactically identical, so you shouldn't have to worry

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-26 06:34

Ok, so here what worked for me:

<xsl:output method="html">
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-26 06:37

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>.

查看更多
登录 后发表回答