Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an attribute with static value with xslt

Tags:

xslt

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.

like image 495
Sergio Romero Avatar asked Aug 17 '11 17:08

Sergio Romero


People also ask

How do I assign a value to a variable in XSLT?

XSLT <xsl:variable>The <xsl:variable> element is used to declare a local or global variable. Note: The variable is global if it's declared as a top-level element, and local if it's declared within a template. Note: Once you have set a variable's value, you cannot change or modify that value!

What is number () in XSLT?

Definition and Usage. The <xsl:number> element is used to determine the integer position of the current node in the source. It is also used to format a number.

What is text () in XSLT?

XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.


1 Answers

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

like image 91
hcayless Avatar answered Oct 19 '22 05:10

hcayless