The <xsl:attribute> is used to add attributes to elements. Thie function replaces the existing attributes with new ones.
Syntax for <xsl:attribute>
<xsl:attribute name=”attributeName” namespace=”uri”>
<!—Template Content -->
</xsl:attribute>
Where,
- name is the name of attribute field. It is mandatory field.
- namespace is the namespace URI for the attribute. It is optional.
The below example add attributes to the item element if it is hand-made or machine-made.
Example of how to use <xsl:attribute>
AttributeAdd.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<factory>
<item>
<name>Toy</name>
<buyingPrice>6</buyingPrice>
<sellingPrice>10</sellingPrice>
</item>
<item>
<name>Box</name>
<buyingPrice>4</buyingPrice>
<sellingPrice>18</sellingPrice>
</item>
<item>
<name>Bag</name>
<buyingPrice>60</buyingPrice>
<sellingPrice>100</sellingPrice>
</item>
<item>
<name>Dress</name>
<buyingPrice>500</buyingPrice>
<sellingPrice>1000</sellingPrice>
</item>
</factory>
AttributeAdd.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="item">
<xsl:if test="name='Toy' or name='Box'">
<item quality="hand-made">
<xsl:apply-templates select="@*|node()"/>
</item>
</xsl:if>
<xsl:if test="name='Bag' or name='Dress'">
<item quality="machine-made">
<xsl:apply-templates select="@*|node()"/>
</item>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Output
<?xml version="1.0"?>
<factory>
<item quality="hand-made">
<name>Toy</name>
<buyingPrice>6</buyingPrice>
<sellingPrice>10</sellingPrice>
</item>
<item quality="hand-made">
<name>Box</name>
<buyingPrice>4</buyingPrice>
<sellingPrice>18</sellingPrice>
</item>
<item quality="machine-made">
<name>Bag</name>
<buyingPrice>60</buyingPrice>
<sellingPrice>100</sellingPrice>
</item>
<item quality="machine-made">
<name>Dress</name>
<buyingPrice>500</buyingPrice>
<sellingPrice>1000</sellingPrice>
</item>
</factory>
Comments
No comments have been made yet.
Please login to leave a comment. Login now