Add attribute with static value using xslt

I need to add an attribute with a static value to all nodes of a certain type in an existing xml file using xslt. Basically something like this:

<root>
  <somenode att1="something" />
  <mynode id="1" att1="value1" att2="value2"/>
  <mynode id="2" att1="value3" att2="value4"/>
</root>

I need this to be like this:

<root>
  <somenode att1="something" />
  <mynode id="1" att1="value1" att2="value2" newatt="static string"/>
  <mynode id="2" att1="value3" att2="value4" newatt="static string"/>
</root>

I looked at this answer , but I could not use it for this case, if it could be used for what I am trying.

I have never used xslt before, I really need help.

Thank.

+5
source share
1 answer
<xsl:template match="mynode">
 <xsl:copy>
  <xsl:attribute name="newatt">static string</xsl:attribute>
  <xsl:apply-templates select="node()|@*"/>
 </xsl:copy>
</xsl:template>

(or something like that) inserted into XSLT that does an identity transformation (see http://www.dpawson.co.uk/xsl/sect2/identity.html ) should do the trick for you.

+7

All Articles