I have the following html:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th>Name</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
</tr>
<tr>
<td> [lastName],[firstName] </td>
<td>[City]</td>
<td>[State]</td>
<td>[Zip]</td>
</tr>
</table>
</body>
</html>
I will get the values from an xml
<person>
<lastName>Zones</lastName>
<firstName>Adam</firstName>
<City>Columbus</City>
<State>OH</State>
<Zip>44250</Zip>
</person>
I want to replace the values in the table data <td>
elements dynamically as:
<td>Zones, Adam</td>
<td>columbus</td>
<td>OH</td>
<td>44250</td>
How to achieve this, Need to change the name,city,state,zip with user entries.
This is rather tedious to do in XSLT 1.0 but certainly possible:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="lookup-doc-path" select="'person.xml'"/>
<xsl:key name="elem-by-name" match="*" use="name()" />
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="td">
<xsl:copy>
<xsl:call-template name="merge">
<xsl:with-param name="string" select="."/>
</xsl:call-template>
</xsl:copy>
</xsl:template>
<xsl:template name="merge">
<xsl:param name="string"/>
<xsl:choose>
<xsl:when test="contains($string, '[') and contains(substring-after($string, '['), ']')">
<xsl:value-of select="substring-before($string, '[')" />
<!-- lookup -->
<xsl:variable name="placeholder" select="substring-before(substring-after($string, '['), ']')" />
<xsl:for-each select="document($lookup-doc-path)">
<xsl:value-of select="key('elem-by-name', $placeholder)" />
</xsl:for-each>
<!-- recursive call -->
<xsl:call-template name="merge">
<xsl:with-param name="string" select="substring-after(substring-after($string, '['), ']')" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$string" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
This is assuming you are directing your XSLT processor to process the HTML document (which must also be a well-formed XML document!) and supplying the path to the XML document containing the actual values as a parameter.
Whether this is the best workflow to have in place is another question.