">
我有以下XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars filter="yes">
<car>
<brand>Volkswagen</brand>
<make>Golf</make>
<wheels>4</wheels>
<extras hifi="yes" ac="no"/>
</car>
</cars>
我想使元素<car>
变平,这样它就只有属性了--不再有子元素了!
到目前为止,我已经生成了这个XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="cars">
<cars>
<xsl:apply-templates/>
</cars>
</xsl:template>
<xsl:template match="car">
<car>
<xsl:for-each select="*">
<xsl:attribute name="{name()}">
<xsl:value-of select="text()"/>
</xsl:attribute>
</xsl:for-each>
</car>
</xsl:template>
</xsl:stylesheet>
这导致:
<cars>
<car brand="Volkswagen" make="Golf" wheels="4" extras=""/>
</cars>
问题:
预期结果:
<cars filter="yes">
<car brand="Volkswagen" make="Golf" wheels="4" hifi="yes" ac="no"/>
</cars>
发布于 2017-11-03 05:01:12
对于第一个问题,在缺少filter
属性的情况下,可以使用标识模板而不是cars
的特定模板来解决这个问题。
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
对于显示为属性的extra
,select语句能否仅选择文本在
<xsl:for-each select="*[normalize-space()]">
最后,对于extras
的属性,添加另一个for -每个属性来获取这些属性。
<xsl:for-each select="*/@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
试试这个XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="car">
<car>
<xsl:for-each select="*[normalize-space()]">
<xsl:attribute name="{name()}">
<xsl:value-of select="text()"/>
</xsl:attribute>
</xsl:for-each>
<xsl:for-each select="*/@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
</car>
</xsl:template>
</xsl:stylesheet>
实际上,这两个xsl:for-each
语句可以在这里组合
<xsl:template match="car">
<car>
<xsl:for-each select="*[normalize-space()]|*/@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
</car>
</xsl:template>
请注意,您假设car
的两个不同的子元素没有相同的属性名。
https://stackoverflow.com/questions/47096363
复制相似问题