Convert Html Table Into Xml Using Xslt
I got stuck with making the two options in converting html table into 2 types of xml. I needed to make a xslt to convert Html table like this 1 row
Solution 1:
You say you have an html source but it's not really a HTML file because you have non-html tags in it (category, dataset)... So something is wrong in your question
Assuming you have an xml source file that you called html in your question, this xsl should do the trick :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml"/>
<!-- Default template -->
<xsl:template match="/">
<chart caption="" xAxisName="City name" yAxisName="Values">
<xsl:attribute name="caption">
<xsl:value-of select="root/table/@caption" />
</xsl:attribute>
<xsl:apply-templates select="root/table/thead"/>
<xsl:apply-templates select="root/table/tbody/tr"/>
</chart>
</xsl:template>
<!-- template for the thead = categories container -->
<xsl:template match="thead">
<categories>
<xsl:apply-templates select="tr/th[@id > 1]" />
</categories>
</xsl:template>
<!-- template for the th = each category -->
<xsl:template match="th">
<category>
<xsl:attribute name="label">
<xsl:value-of select="." />
</xsl:attribute>
</category>
</xsl:template>
<!-- template for the tr = the dataset -->
<xsl:template match="tr">
<dataset seriesName="">
<xsl:attribute name="seriesName">
<xsl:value-of select="td[@id=1]" />
</xsl:attribute>
<xsl:apply-templates select="td[@id > 1]" />
</dataset>
</xsl:template>
<!-- template for the td = the set tag -->
<xsl:template match="td">
<set value="">
<xsl:attribute name="value">
<xsl:value-of select="." />
</xsl:attribute>
</set>
</xsl:template>
</xsl:stylesheet>
But you have to know that a well formed xml has a root element, so I took your xml source surrounded by a root
element :
<root>
<categories>1 row</categories>
<dataset>1 column</dataset>
<table caption="City statistics">
<thead>
<tr>
<th id="1">Name</th>
<th id="2">Population</th>
<th id="3">Area</th>
<th id="4">Elevation</th>
</tr>
</thead>
<tbody>
<tr>
<td id="1">Moscow</td>
<td id="2">4.7</td>
<td id="3">11.54</td>
<td id="4">13</td>
</tr>
<tr>
<td id="1">London</td>
<td id="2">6</td>
<td id="3">15.54</td>
<td id="4">15</td>
</tr>
</tbody>
</table>
</root>
Post a Comment for "Convert Html Table Into Xml Using Xslt"