【发布时间】:2017-06-16 18:59:46
【问题描述】:
在将元素转换为属性时,我正在检查父元素的名称是否存在于我们尝试转换为属性的元素中。
planet_name 等示例是元素,它包含父元素(行星),因此需要将其转换为属性,否则按原样。
我编写了 xslt,但它无法正常工作,有人可以帮忙吗?提前致谢。
示例 XML 示例:
<world>
<planet>
<planet_name>solaris</plante_name>
<planet_number>23</plante_number>
<test>value1</test>
</planet>
</world>
预期输出:
<world>
<planet planet_name="solaris" planet_number="23">
<test>value1</test>
</planet>
</world>
XSLT 如下
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" />
<xsl:strip-space elements="*" />
<!--Identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<!--Match elements that contain children elements that don't contain children
elements themselves. -->
<xsl:template match="*[*[not(*)]]">
<xsl:copy>
<xsl:for-each select="*">
<xsl:variable name="attrName" select="name()" />
<xsl:variable name="parentName" select="name(..)" />
<xsl:choose>
<xsl:when test="contains(normalize-space($parentName),normalize-space($attrName))">
<xsl:attribute name="{name()}">
<xsl:value-of select="$parentName" />
</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="node()" />
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
【问题讨论】:
-
您是否至少有一个格式良好的输入样本,以便我们建议的任何 XSLT 都有机会处理输入?
-
solaris 23 value1 -
添加了格式良好的 XML 示例。如果 xslt 中有任何错误,请您帮忙