通过 XSLT 从 XML 中删除空标签 [英] Removing empty tags from XML via XSLT
本文介绍了通过 XSLT 从 XML 中删除空标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个以下模式的 xml
I had an xml of the following pattern
<?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(来自论坛)
I used the following xslt (got from forums) in my attempt to remove empty tags
<xsl:template match="@*|node()">
<xsl:if test=". != '' or ./@* != ''">
<xsl:copy>
<xsl:copy-of select = "@*"/>
<xsl:apply-templates />
</xsl:copy>
</xsl:if>
使用的 xslt 成功删除了
The xslt used is successful in removing tags like
<Title/>
<Role></Role>
...但是当空标签在两行时失败,例如:
...but fails when empty tags are on two lines, eg:
<Department>
</Department>
有没有办法解决这个问题?
Is there any fix for this?
推荐答案
这种转换根本不需要任何条件 XSLT 指令,也没有使用明确的优先级:
This transformation doesn't need any conditional XSLT instructions at all and uses no explicit priorities:
<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 从 XML 中删除空标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文