The following example shows a basic XSLT transformation from one XML to another with a different structure.
Prerequisites
I’m assuming that the reader has the following skills:
Basic Transformation
Let’s begin with this XML:
Reservation.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="UTF-8"?> <Reservation> <reservation id="123456789" /> <arrivingDate>03-09-2012</arrivingDate> <departureDate>03-15-2012</departureDate> <guestName>Fred</guestName> <guestLastName>Davis</guestLastName> <hotelID>03</hotelID> <room>1001</room> <oceanView>true</oceanView> <smokingArea>false</smokingArea> </Reservation> |
And we want to transform it into a different XML, like this:
ReservationInfo.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="UTF-8"?> <ReservationInfo> <reservation id="123456789" arrivalDate="03-09-2012" departureDate="03-15-2012" /> <guest> <name>Fred</name> <lastName>Davis</lastName> </guest> <room number="1001"> <oceanView>true</oceanView> <smokingArea>false</smokingArea> </room> </ReservationInfo> |
It’s the same data but in different order. To obtain this result, we need a XSLT transformation like this:
Transformation.xslt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" /> <xsl:template match="/"> <ReservationInfo> <reservation> <xsl:attribute name="id"> <xsl:value-of select='Reservation/reservation/@id' /> </xsl:attribute> <xsl:attribute name="arrivalDate"> <xsl:value-of select='Reservation/arrivingDate' /> </xsl:attribute> <xsl:attribute name="departureDate"> <xsl:value-of select='Reservation/departureDate' /> </xsl:attribute> </reservation> <guest> <name> <xsl:value-of select="Reservation/guestName" /> </name> <lastName> <xsl:value-of select="Reservation/guestLastName" /> </lastName> </guest> <room> <xsl:attribute name="number"> <xsl:value-of select='Reservation/room' /> </xsl:attribute> <oceanView> <xsl:value-of select="Reservation/oceanView" /> </oceanView> <smokingArea> <xsl:value-of select="Reservation/smokingArea" /> </smokingArea> </room> </ReservationInfo> </xsl:template> </xsl:stylesheet> |
You can notice a few things about the XSLT above:
- You have to write your new XML tree and populate it with the values of the old one.
- The tag xsl:value-of select=”” is the basic selector for getting information about a node or attribute.
- If you want to insert an attribute inside a node, follow the steps from line 29 to 31
- To get the value of an attribute, add an @ before the name of the attribute. Look at line 10
Cheers!
3 comments: On XSLT 1.0 Basic Transformation Example
I want to parse a xml which have repeated set of Reservation section as below :
03-09-2012
03-15-2012
Fred
Davis
03
1001
true
false
03-09-2012
03-15-2012
ABC
XYZ
04
1002
true
false
oa5d1t
klkeyp