I'm trying to format an HTML table by adding some CSS classes from a SQL Query using XML PATH syntax.
I tried to apply the answer found on: Assign CSS class to HTML tags generated with SQL 'FOR XML' but I don't know what I'm doing wrong:
DECLARE @tableHTML NVARCHAR(MAX) ;
SET @tableHTML =
N'<table border="0" cellpadding="4" style="font-size:12px; font-family:Arial">' +
N'<tr>' +
N'<th style="border-bottom:1px solid #7AC0DA">Activity Date</th>' +
N'<th style="border-bottom:1px solid #7AC0DA">Lead</th>' +
N'<th style="border-bottom:1px solid #7AC0DA">Lead By</th>' +
N'<th style="border-bottom:1px solid #7AC0DA">Activity Title</th>' +
N'<th style="border-bottom:1px solid #7AC0DA">Featured On</th>' +
CAST ( (SELECT 'trclass' as [@class],
(SELECT StartDate as [*], 'tdclass' as [@class] FOR XML PATH('td'), type),
(SELECT LeadGroup as [*], 'tdclass' as [@class] FOR XML PATH('td'), type),
(SELECT LeadBy as [*], 'tdclass' as [@class] FOR XML PATH('td'), type),
(SELECT Title as [*], 'tdclass' as [@class] FOR XML PATH('td'), type),
(SELECT Featured as [*], 'tdclass' as [@class] FOR XML PATH('td'), type)
FROM @Activites ORDER BY [StartDate],[LeadGroup],[LeadBy]
FOR XML PATH('tr') , TYPE
) AS NVARCHAR(MAX) ) +
N'</table>';
I would like to have an output like this:
<table>
<tr>
<th style="border-bottom:1px solid #7AC0DA">Activity Date</th>
<th style="border-bottom:1px solid #7AC0DA">Lead</th>
<th style="border-bottom:1px solid #7AC0DA">Lead By</th>
<th style="border-bottom:1px solid #7AC0DA">Activity Title</th>
<th style="border-bottom:1px solid #7AC0DA">Featured</th>
<tr>
<tr clas="trclass">
<td clas="tdclass">2016-01-01</td>
<td clas="tdclass">Marketing</td>
<td clas="tdclass">John Smith</td>
<td clas="tdclass">Project XYZ</td>
<td clas="tdclass">Web - Magazine</td>
</tr>
</table>
However, I'm getting the following error when executing the query:
Attribute-centric column '@style' must not come after a non-attribute-centric sibling in XML hierarchy in FOR XML PATH
What am I doing wrong? I must say I'm a little confused on how XML PATH works. Thanks!