How to set attribute in XML using XSLT?
Asked Answered
E

3

41

For example, I want to add an attribute to this node:

<Party>

So it will look like:

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

Attribute value has to come from XPath.

The following will not work :)

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

How to do that?

Episode answered 20/6, 2013 at 11:31 Comment(0)
J
56

Attributes of literal result elements support the attribute value template syntax, using {}:

<Party role="{some/xpath/path}">
Junco answered 20/6, 2013 at 11:39 Comment(0)
M
14
<xsl:template match="Party">
  <Party role="{some/xpath/path}">
    <xsl:apply-templates select="@* | node()"/>
  </Party>
</xsl:template>

should do. As an alternative

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

Of course the apply-templates is only necessary if there are attribute and/or child nodes you also want to be processed (for example to be copied by an identity transformation template).

Manno answered 20/6, 2013 at 11:39 Comment(0)
V
8

you can try the below sample:

<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> 

Here I am setting the attribute role to a xml node Party.

Variation answered 26/9, 2017 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.