SQL Server for xml path add attributes and values

2020-03-01 08:54发布

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

4条回答
姐就是有狂的资本
2楼-- · 2020-03-01 09:11

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

查看更多
Deceive 欺骗
3楼-- · 2020-03-01 09:12

This helps you

SELECT TOP 1 
   'someValue' AS '@Attribute',
   'text' 
FOR XML PATH('YourElement'), ROOT('Root')
查看更多
一纸荒年 Trace。
4楼-- · 2020-03-01 09:16

The following script enables you to extract all your data from all tables in your database into a single XML file:

SET NOCOUNT ON 
DECLARE @CMD varchar(max) = ''

DECLARE @AllTablesXML table (XMLData XML)
SELECT @CMD += 
  ';SELECT '''+TABLE_NAME+''' as ''@name'' ,
    (
    SELECT * 
    FROM ' + QUOTENAME(T.TABLE_SCHEMA) + '.' + QUOTENAME(T.TABLE_NAME) +
    'FOR XML PATH (''Columns'') ,type ' + CHAR(10) + '
    )
   FOR XML PATH (''Table''),  type'
   FROM INFORMATION_SCHEMA.TABLES T
  --WHERE T.TABLE_NAME in  ('your List of tables') Uncomment if you need to extract specific tables

INSERT INTO @AllTablesXML
EXEC (@CMD) 


SELECT XMLData 
FROM @AllTablesXML
FOR XML PATH (''), ROOT('Alltables') 
查看更多
We Are One
5楼-- · 2020-03-01 09:33
select 'hello' as [@attr1]
, 'world'
for xml path('mynode')
查看更多
登录 后发表回答