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

Vex*_*toR 24 xml xslt xpath xslt-2.0

例如,我想为此节点添加一个属性:

<Party>
Run Code Online (Sandbox Code Playgroud)

所以它看起来像:

<Party role="this should be set using XPath">
Run Code Online (Sandbox Code Playgroud)

属性值必须来自XPath.

以下将无法正常工作:)

<Party role=<xsl:value-of select="some/xpath/path"/>>
Run Code Online (Sandbox Code Playgroud)

怎么做?

Ian*_*rts 39

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

<Party role="{some/xpath/path}">
Run Code Online (Sandbox Code Playgroud)


Mar*_*nen 11

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

应该做.作为备选

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

当然,只有在您还希望处理属性和/或子节点时(例如,要通过身份转换模板进行复制),才需要apply-templates.


小智 6

您可以尝试以下示例:

<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> 
Run Code Online (Sandbox Code Playgroud)

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