Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: How to change an attribute value during <xsl:copy>?

I have an XML document, and I want to change the values for one of the attributes.

First I copied everything from input to output using:

<xsl:template match="@*|node()">   <xsl:copy>     <xsl:apply-templates select="@*|node()"/>   </xsl:copy> </xsl:template> 

And now I want to change the value of the attribute "type" in any element named "property".

like image 790
tomato Avatar asked Mar 05 '09 18:03

tomato


People also ask

How does xsl copy work?

Definition and Usage. The <xsl:copy> element creates a copy of the current node. Note: Namespace nodes of the current node are automatically copied as well, but child nodes and attributes of the current node are not automatically copied!

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

This problem has a classical solution: Using and overriding the identity template is one of the most fundamental and powerful XSLT design patterns:

<xsl:stylesheet version="1.0"   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">     <xsl:output omit-xml-declaration="yes" indent="yes"/>      <xsl:param name="pNewType" select="'myNewType'"/>      <xsl:template match="node()|@*">         <xsl:copy>             <xsl:apply-templates select="node()|@*"/>         </xsl:copy>     </xsl:template>      <xsl:template match="property/@type">         <xsl:attribute name="type">             <xsl:value-of select="$pNewType"/>         </xsl:attribute>     </xsl:template> </xsl:stylesheet> 

When applied on this XML document:

<t>   <property>value1</property>   <property type="old">value2</property> </t> 

the wanted result is produced:

<t>   <property>value1</property>   <property type="myNewType">value2</property> </t> 
like image 125
Dimitre Novatchev Avatar answered Oct 19 '22 19:10

Dimitre Novatchev