Tuesday, October 4, 2011

XML to HTML using XSLT























Check out the most simple Example using which you can convert your XML to HTML.
For this transition if you will use the XSLT, it will be really easy for you.

Assume that following is the XML from which you want to read data and convert it to HTML.

inputxml.xml


  <Persons>

  <Person image="http://someIMageURL">

    <Name>Kavita  </Name>

    <Phone>123123  </Phone>

  </Person>

  <Person image="http://someIMageURL">

    <Name>Kavita1  </Name>

    <Phone>456  </Phone>

  </Person>

  <Person image="http://someIMageURL">

    <Name>Kavita2  </Name>

    <Phone>23423  </Phone>

  </Person>

  <Person image="http://someIMageURL">

    <Name>Kavita3  </Name>

    <Phone>99090  </Phone>

  </Person>

  </Persons>

Now if you write XSLT as below.

   <?xml version="1.0"?>

   <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output doctype-public="HTML"/>

   <xsl:template match="Persons">

   <table border="1">

    <tr>
     <td>Sr.no   </td>
     <td>Name   </td>
     <td>Phone   </td>
     <td>Image   </td>

   </tr>

   <xsl:for-each select="Person">

   <tr>

   <td>

   <xsl:value-of select="position()"/>

   </td>

   <td>

   <xsl:value-of select="Name"/>

   </td>

   <td>

   <xsl:value-of select="Phone"/>

   </td>

   <td>

   <xsl:value-of select="@image"/>

   </td>

   </tr>

   </xsl:for-each>

   </table>

   </xsl:template>

   </xsl:stylesheet>

And apply it in the above mentioned XML then you will get an HTML output as following

Sr.noNamePhoneImage
1Kavita123123http://someIMageURL
2Kavita1456http://someIMageURL
3Kavita223423http://someIMageURL
4Kavita399090http://someIMageURL





No comments:

Post a Comment