Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set attribute in XML using XSLT?

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?

like image 711
VextoR Avatar asked Jun 20 '13 11:06

VextoR


People also ask

What is attribute in XSLT?

The <xsl:attribute> element creates an attribute in the output document, using any values that can be accessed from the stylesheet. The element must be defined before any other output document element inside the output document element for which it establishes attribute values.

What is one way to add an attribute to an element in XSLT?

Attributes can be added or modified during transformation by placing the <xsl:attribute> element within elements that generate output, such as the <xsl:copy> element. Note that <xsl:attribute> can be used directly on output elements and not only in conjunction with <xsl:element> .

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.

How do I apply a template in XSLT?

The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a "select" attribute to the <xsl:apply-templates> element, it will process only the child elements that matches the value of the attribute.


2 Answers

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

<Party role="{some/xpath/path}"> 
like image 73
Ian Roberts Avatar answered Oct 10 '22 03:10

Ian Roberts


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

like image 26
Martin Honnen Avatar answered Oct 10 '22 01:10

Martin Honnen