Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server for xml path add attributes and values

I want to create an xml node that contains attributes as well as values.

Example:

<mynode attr1="hello">world</mynode>

I understand that

SELECT 'hello' as '@attr1' 

creates at least mynode, but how to attach "world" then?

I tried

SELECT 'world' as 'mynode/[@attr1=hello]' 

but it didn't work

like image 232
tuxmania Avatar asked Aug 11 '14 06:08

tuxmania


2 Answers

This is a basic example:

SELECT ( SELECT 'White' AS Color1,
'Blue' AS Color2,
'Black' AS Color3,
'Light' AS 'Color4/@Special',
'Green' AS Color4,
'Red' AS Color5
 FOR
 XML PATH('Colors'),
 TYPE
 ),
 ( SELECT 'Apple' AS Fruits1,
 'Pineapple' AS Fruits2,
 'Grapes' AS Fruits3,
 'Melon' AS Fruits4
 FOR
 XML PATH('Fruits'),
 TYPE
 )
 FOR XML PATH(''),
 ROOT('SampleXML')

How to create XML data in SQL SERVER


Please, for more information you can visit this page SQL SERVER – Simple Example of Creating XML File Using T-SQL

like image 64
Orlando Herrera Avatar answered Oct 27 '22 00:10

Orlando Herrera


This helps you

SELECT TOP 1 
   'someValue' AS '@Attribute',
   'text' 
FOR XML PATH('YourElement'), ROOT('Root')
like image 26
okanguz Avatar answered Oct 26 '22 23:10

okanguz