例如:
<a>
<b>
<aaa>val</aaa>
<bbb></bbb>
</b>
</a>
我想要一个 xslt,它仅在源代码中包含值时才会创建 aaa、bbb、ccc 标签。
到目前为止我用过:
<aaa><xsl:value-of select="//aaa"/></aaa>
<bbb><xsl:value-of select="//bbb"/></bbb>
<ccc><xsl:value-of select="//ccc"/></ccc>
这显然不好。
最佳答案
对您想要实现的目标做出一些假设(恐怕您没有说得那么清楚),下面的解决方案应该有效。
输入
<a>
<b>
<aaa>val</aaa>
<bbb></bbb>
</b>
</a>
样式表非常动态,即不依赖于实际的元素名称,但它依赖于 XML 文档的结构。
样式表(“动态”)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*|/*/*">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*/*/*[not(text())]"/>
<xsl:template match="/*/*/*[text()]">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
另一方面,如果元素名称事先已知并且不更改,则可以在样式表中使用它们:
样式表(“静态”元素名称)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/a|b">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="aaa|bbb">
<xsl:choose>
<xsl:when test="text()">
<xsl:copy-of select="."/>
</xsl:when>
<xsl:otherwise/>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
输出
<?xml version="1.0" encoding="UTF-8"?>
<a>
<b>
<aaa>val</aaa>
</b>
</a>
关于java - 仅当源中存在值时才创建标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355112/