如何使用XSLT在XML中设置属性?

40
例如,我想要给这个节点添加一个属性:
<Party>

那么它将会看起来像这样:

<Party role="this should be set using XPath">

属性值必须来自XPath。

以下方法不起作用 :)

<Party role=<xsl:value-of select="some/xpath/path"/>>

如何做到这一点?

3个回答

55

文本结果元素的属性支持使用{}属性值模板语法:

<Party role="{some/xpath/path}">

14
<xsl:template match="Party">
  <Party role="{some/xpath/path}">
    <xsl:apply-templates select="@* | node()"/>
  </Party>
</xsl:template>

应该这样做。作为一个替代方案

<xsl:template match="Party">
  <xsl:copy>
    <xsl:attribute name="role" select="some/xpath/path"/>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

当然,apply-templates 只有在您还想处理属性和/或子节点时才是必需的(例如,通过标识转换模板进行复制)。


8
你可以尝试以下示例:
<xsl:for-each select="YOUR_SELECT_PATH"> 
  <a> 
    <Party> <xsl:attribute name="role"><xsl:value-of select="@source"/></xsl:attribute> </Party>
    <xsl:value-of select="."/> 
  </a> 
</xsl:for-each> 

在这里,我将属性角色设置为一个XML节点Party。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接