singhsac singhsac - 1 year ago 46
CSS Question

Assign CSS class to HTML tags generated with SQL 'FOR XML'

I am getting table rows and table data (with HTML tags) from SQL using 'FOR XML'. Is there a way I could assign CSS classes to the html tags in SQL?

What I am currently getting:


SQL query:

SELECT (SELECT [Name] as [td] FOR XML PATH(''), type),
(SELECT [Value] as [td] FOR XML PATH(''), type)
FROM table

Desired output:

<tr class="test1"><td class="test2">Name</td><td class="test3">Value</td></tr>

Answer Source

I know I am answering my own question, thought it may help someone else.

I'm adding class as an attribute to XML nodes which is giving me the desired output.

SELECT  'test1' AS [@class]
    , ( SELECT  'test2' as [@class]
        , (SELECT 'Name' FOR XML PATH(''))
        FOR XML PATH('td'), type)
    ,(SELECT  'test3' as [@class]
        , (SELECT 'Value' FOR XML PATH(''))
        FOR XML PATH('td'), type) 
FOR XML PATH('tr'), type

<tr class="test1"><td class="test2">Name</td><td class="test3">Value</td></tr>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download