How to eliminate all <TAG/> and all attribute=“” by XSLT?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 05:08:00

问题


In a xsl:stylesheet I have this "identity like" transform, to eliminate comments, empty (terminal) tags and empty attributes... But the second xsl:when not works

  <xsl:template match="node()">
  <xsl:choose>
    <xsl:when test="name()='p' and not(./*) and not(normalize-space(.))"></xsl:when>
    <xsl:when test="not(name()='img') and not(name()='br') and not(./*) and not(text())"
    ></xsl:when> <!-- this line NOT WORKS -->
    <xsl:otherwise><xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy></xsl:otherwise>
  </xsl:choose>
  </xsl:template>

  <xsl:template match="@*">
  <xsl:choose>
    <xsl:when test="not(normalize-space(.))"></xsl:when>
    <xsl:otherwise><xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy></xsl:otherwise>
  </xsl:choose>
  </xsl:template>

  <xsl:template match="comment()"></xsl:template>

Whow to express condition to empty tags in this context?

PS: the "empty rules" are explained here, I try to use it, but not see why not working.


回答1:


An empty element is an element with no child nodes.

Template match priority is your friend ... the following should be the kind of identity stylesheet that meets your description plus what I think you are doing with image and break elements.

<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

<!--toss these-->
<xsl:template match="comment() | 
                    *[not(node())] |
                    @*[not(normalize-space())]"/>

<!--preserve these-->
<xsl:template match="img|br" priority="1">
  <xsl:call-template name="identity"/>
</xsl:template>

<!--preserve everything else-->
<xsl:template match="@*|node()" name="identity">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>


来源:https://stackoverflow.com/questions/18025375/how-to-eliminate-all-tag-and-all-attribute-by-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!