0

The FOR XML command uses column names to create the XML nodes. I need my nodes to be named after values I'm getting from the database. As far as I know you can't do something such as

SELECT Key AS Section

SECTION         | KEY                | VALUE
-----------------------------------------------------------
PageAddProduct  |   ErrorDateFormat  |  Incorrect value
PageAddProduct  |   ErrorNotSelected |  Please select value
WidgetLogin     |   Title            |  Connexion
WidgetLogin     |   MailLabel        |  Mail

This is the desired XML output

<Resources>
  <WidgetLogin>
    <Title>Connexion</Title>
    <MailLabel>Mail</MailLabel>
  </WidgetLogin>
</Resources>

Not sure if you can get this with For Xml. Help would be much appreciated.

2 Answers 2

1

You can build your XML as a string and then cast to XML.

This sample code will work in SQL Server 2012 since it is using the concat function but it can easily be rewritten to use + instead.

select cast(concat('<Resources>',
                   (
                   select concat('<',T1.SECTION,'>',
                                 (
                                 select concat('<',T2.[KEY],'>',
                                               (select T2.VALUE for xml path('')),
                                               '</',T2.[KEY],'>')
                                 from T as T2
                                 where T1.SECTION = T2.SECTION
                                 for xml path(''), type
                                 ).value('text()[1]', 'nvarchar(max)'),
                                 '</',T1.SECTION,'>')
                   from T as T1
                   group by T1.SECTION
                   for xml path(''), type
                   ).value('text()[1]', 'nvarchar(max)'),
                   '</Resources>') as xml)

SQL Fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You can use FOR XML like below:

SELECT Section as Title, Value as MailLabel
FROM table
FOR XML PATH('WidgetLogin'), ROOT('Resources'), TYPE 

1 Comment

That will work specifically for the 'WidgetLogin' section, I can potentially have hundreds of sections and values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.