【发布时间】:2020-03-27 19:09:37
【问题描述】:
我知道网上有很多关于如何使用 XSLT 删除空 XML 元素的示例,但是我找不到适用于我的文档的方法。我创建了编写新元素的模板,并希望处理一个最终模板,该模板匹配所有内部没有文本内容的元素,这包括子元素。如果一个元素包含一个没有文本的子元素,我希望只删除空的子元素。我尝试过使用识别转换,但它们似乎不适用于我设置模板的方式,但我想保留这种结构。
XML
<fruitSet>
<fruit>
<name>apple</name>
<colour>green</colour>
<ratings>
<taste>10</taste>
<look>8</look>
</ratings>
</fruit>
<fruit>
<name>strawberry</name>
<colour>red</colour>
<ratings>
<taste>7</taste>
<look>5</look>
</ratings>
</fruit>
<fruit>
<name>Orange</name>
<colour></colour>
<ratings>
<taste>3</taste>
<look></look>
</ratings>
</fruit>
</fruitSet>
XSL
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsd ="http://www.w3.org/2001/XMLSchema#">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<RDF>
<xsl:apply-templates select = "fruitSet/fruit"/>
<xsl:apply-templates select = "fruitSet/fruit/ratings"/>
</RDF>
</xsl:template>
<xsl:template match = "fruit">
<Description>
<xsl:attribute name = "ID">
<xsl:value-of select = "name/text()"/>
</xsl:attribute>
<hasColour><xsl:value-of select = "colour/text()"/></hasColour>
<hasTasteRating>
<xsl:apply-templates select = "ratings"/>
</hasTasteRating>
</Description>
</xsl:template>
<xsl:template match = "ratings">
<xsl:value-of select = "taste/text()"/>
</xsl:template>
</xsl:stylesheet>
期望的输出
<?xml version="1.0" encoding="utf-16"?>
<RDF xmlns:xsd="http://www.w3.org/2001/XMLSchema#">
<Description ID="apple">
<hasColour>green</hasColour>
<hasTasteRating>10</hasTasteRating>
</Description>
<Description ID="strawberry">
<hasColour>red</hasColour>
<hasTasteRating>7</hasTasteRating>
</Description>
<Description ID="Orange">
<hasTasteRating>3</hasTasteRating>
</Description>1073</RDF>
</RDF>
【问题讨论】: