Change same tags name into different tags in xml using xslt
Hi All,
Today we will learn about converting same tags of xml can be dynamically change into different tags.
Today we will learn about converting same tags of xml can be dynamically change into different tags.
We will see one example here to convert same tags of xml
into different tags.
Let’s start with an example:
Input XML:
<books>
<book>
<name>value1</name>
<name>value2</name>
<name>value3</name>
<name>value4</name>
<name>value5</name>
</book>
<book>
<name>value1</name>
<name>value2</name>
<name>value3</name>
<name>value4</name>
<name>value5</name>
</book>
</books>
We can easily see here that if we want to get the value of name
tag it won’t be easy. To get the value of name tags from the xml we can easily
convert the name tag dynamically using the xslt.
To convert this xml “name” tag we will use XSLT:
<?xml version="1.0"
encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="name">
<xsl:variable
name="ename">
<xsl:text>column</xsl:text>
<xsl:number
count="name"/>
</xsl:variable>
<xsl:element
name="{$ename}">
<xsl:value-of
select="."/>
</xsl:element>
</xsl:template>
When we will use this xslt to xml it will give us this
output:
<book>
<column1>value1</column1>
<column2>value2</column2>
<column3>value3</column3>
<column4>value4</column4>
<column5>value5</column5>
</book>
<book>
<column1>value1</column1>
<column2>value2</column2>
<column3>value3</column3>
<column4>value4</column4>
<column5>value5</column5>
</book>
Please observe that we have changed the name to the column tag
and its coming out like column1, column2, column3 … . so now we can easily
extract the value of this different tags.
Hope you like this blog and plase share your feedback in
comment.
Regards,
Ankit Gupta
Comments
Post a Comment