XSLT 转换后从生成的 XML 中删除空标签

Remove empty tags from generated XML after XSLT transformation

我正在使用 XSLT 将输入 XML 转换为输出 XML。我的要求是在从输入进行 XSLT 转换期间,我需要从输出 XML 中删除所有空标签。

我试过这里给出的说明


但这可能是在讨论我们只编写 XSLT 来从 XML 中删除空标签的场景。在我的例子中,我将不得不在从输入 XML 转换为输出 XML 时消除空标签(在用于转换的同一个 XSLT 中)。你能建议我怎么做吗?

在 XSLT 3 中,使用 xsl:where-populated 作为元素匹配中身份转换的“包装器”就足够了:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">
    
  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="*">
      <xsl:where-populated>
          <xsl:copy>
              <xsl:apply-templates select="@*"/>
              <xsl:apply-templates/>
          </xsl:copy>
      </xsl:where-populated>
  </xsl:template>
  
  <xsl:template match="foo"/>
  
</xsl:stylesheet>