XSL:来自随机元素或其他属性值的属性名称

时间:2013-12-29 12:05:17

标签: attributes element

我需要将element的值发送给属性,该属性覆盖该属性名称。属性的值保持不变。

示例:

<engine hybrid="yes">
  <A>2000</A>
  <B>diesel</B>
  <C>160</C>
</engine>

我需要实现的目标,例如:

<engine diesel="yes">
  <A>2000</A>
  <B>diesel</B>
  <C>160</C>
</engine>

提前致谢!

1 个答案:

答案 0 :(得分:0)

您应该将转换基于身份模板,它会将输入中的所有内容复制到输出中,除非此行为被更具体的模板覆盖,否则

<xsl:template match="@*|node()">
  <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
</xsl:template>

有了这个,您就可以为engine元素添加特定模板

<xsl:template match="engine">
  <engine>
    <!-- create an attribute whose name is taken from the first B child -->
    <xsl:attribute name="{B}">yes</xsl:attribute>
    <!-- and continue processing child nodes (but not other attributes) -->
    <xsl:apply-templates />
  </engine>
</xsl:template>

此处需要注意的关键是name的{​​{1}}属性被视为“属性值模板” - 您可以将值的一部分括在大括号xsl:attribute中部件将被评估为XPath表达式,而不是作为文字值。

最后,当然,您应该注意,这仅在{}的内容是有效的XML属性名称时才有效(因此没有空格,没有B=这样的字符,它不能以数字开头。

相关问题