xslt - 通过 XSLT 从 XML 中删除空标签

标签 xslt

我有以下模式的 xml

<?xml version="1.0" encoding="UTF-8"?>
    <Person>
      <FirstName>Ahmed</FirstName>
      <MiddleName/>
      <LastName>Aboulnaga</LastName>
      <CompanyInfo>
        <CompanyName>IPN Web</CompanyName>
        <Title/>
    <Role></Role>
        <Department>
    </Department>
      </CompanyInfo>
    </Person>

我在尝试删除空标签时使用了以下 xslt(来自论坛)

 <xsl:template match="@*|node()">
<xsl:if test=". != '' or ./@* != ''">
  <xsl:copy>
  <xsl:copy-of select = "@*"/>
    <xsl:apply-templates />
  </xsl:copy>
</xsl:if>


使用的 xslt 成功删除标签,如
<Title/>
    <Role></Role>

...但是当空标签在两行时失败,例如:
<Department>
    </Department>

有什么解决办法吗?

最佳答案

这种转换根本不需要任何条件 XSLT 指令,也没有使用明确的优先级:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match=
    "*[not(@*|*|comment()|processing-instruction()) 
     and normalize-space()=''
      ]"/>
</xsl:stylesheet>

应用于提供的 XML 文档时 :
<Person>
    <FirstName>Ahmed</FirstName>
    <MiddleName/>
    <LastName>Aboulnaga</LastName>
    <CompanyInfo>
        <CompanyName>IPN Web</CompanyName>
        <Title/>
        <Role></Role>
        <Department>
        </Department>
    </CompanyInfo>
</Person>

它产生了想要的、正确的结果 :
<Person>
   <FirstName>Ahmed</FirstName>
   <LastName>Aboulnaga</LastName>
   <CompanyInfo>
      <CompanyName>IPN Web</CompanyName>
   </CompanyInfo>
</Person>

关于xslt - 通过 XSLT 从 XML 中删除空标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6648679/

相关文章:

xml - XSLT:<xsl:element name ="a"> 和 <a> 之间的区别

javascript - 使用 javascript 加载 XSL 文件

xslt - 是否有调用单参数 XSL 函数的快捷方式?

xml - 需要更换命名空间

css - 分页问题

xml - XSLT 函数以 YYYYMMDD 格式验证日期

html - XSLT 转换从混合内容中移除 HTML 元素

css - for-each 中的 xsl 使用不同的 css 类

java - JVM 使用哪个根目录来解析相对 URL?

xslt - 将 Xalan 替换为 Saxon for XSL with Java-Extension