6

I need to add an attribute with a static value to all nodes of a specific 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 it to be like so:

<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 took a look at this answer but I was not able to use it for this case, if it could be used for what I'm trying.

I've never used xslt before, I really need some help.

Thanks.

Community
  • 1
  • 1
Sergio Romero
  • 6,477
  • 11
  • 41
  • 71

1 Answers1

9
<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 an XSLT that does an identity transform (see http://www.dpawson.co.uk/xsl/sect2/identity.html) should do the trick for you.

marioosh
  • 27,328
  • 49
  • 143
  • 192
hcayless
  • 1,036
  • 6
  • 7
  • +1 - The only thing I would change is: `` – Daniel Haley Aug 17 '11 at 17:44
  • Thanks hcayless it did add the new attribute but also had a side effect. Now I also have an xmlns:xsd="http://www.w3.org/2001/XMLSchema" namespace. How can I prevent that from being added as well? – Sergio Romero Aug 17 '11 at 17:49
  • you could try adding the attribute exclude-result-prefixes="xsd" to your xsl:stylesheet element. Or (assuming it's boilerplate and you don't need that namespace declaration) you could just remove it from the XSLT. – hcayless Aug 17 '11 at 18:58
  • @DevNull: I don't think the `select` attribute is allowed on ``. See http://www.w3.org/TR/xslt#creating-attributes – LarsH Aug 17 '11 at 19:28
  • @LarsH: I always forget that the `select` attribute on `xsl:attribute` is XSLT 2.0 only. http://www.w3.org/TR/xslt20/#element-attribute – Daniel Haley Aug 17 '11 at 20:10
  • @DevNull: thx, I didn't know it was allowed in XSLT 2.0. Was too lazy to check both specs. – LarsH Aug 17 '11 at 20:58