Luck
Luck

Reputation: 23

xml to html in table format using xslt

I am new to xslt, need to convert xml data into html table format like element name and data as table columns, I have working code which show in text but the same I am looking for html table format please find the xml and xslt

currently getting output like this, please suggest how I can get this

A_B Text
A_C Text
A_D_D1 = Text
A_D_D2_D3 Text
A_D_D2_D4 Text
A_E_E1_E2_E3 = Text

but the same I am need to show in html table format

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="recur.xsl"?>
<A>
   <B>Text</B>
   <C>Text</C>
   <D>
      <D1>Text</D1>
      <D2>
          <D3>Text</D3>
          <D4>Text</D4>
      </D2>
   </D>
   <E>
      <E1>
          <E2>
              <E3>Text</E3>
          </E2> 
      </E1>
   </E>
</A>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*[text()]">
    <xsl:for-each select="ancestor-or-self::*">
        <xsl:value-of select="name()" />
        <xsl:if test="position()!=last()">
            <xsl:text>_</xsl:text>
        </xsl:if>
    </xsl:for-each>
    <xsl:text> </xsl:text>
    <xsl:value-of select="." />
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>
</xsl:stylesheet>

Expected output is like this

<html>
 </head>
 <body>
 <table border="1">
 <tr><td>A_B</td> <td> Text </td>
 <tr><td>A_C</td> <td> Text </td>
 <tr><td>A_D_D1</td> <td> Text </td>
 <tr><td>A_D_D2_D3</td> <td> Text </td>
 <tr><td>A_D_D2_D4</td> <td> Text </td>
 <tr><td>A_E_E1_E2_E3</td> <td> Text </td>
 </table>
 </body>
</html>

Upvotes: 2

Views: 1021

Answers (1)

hr_117
hr_117

Reputation: 9627

You may try this (may only work for input example):

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
  <table>
    <xsl:apply-templates select="*"/>
  </table>
</xsl:template>

<xsl:template match="*[text()]">
  <tr>
    <td>
    <xsl:for-each select="ancestor-or-self::*">
        <xsl:value-of select="name()" />
        <xsl:if test="position()!=last()">
            <xsl:text>_</xsl:text>
        </xsl:if>
    </xsl:for-each>
    </td>
    <td>
    <xsl:value-of select="." />
    </td>
  </tr>
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>
</xsl:stylesheet>

Upvotes: 0

Related Questions