0
我想從xml中的所有數據轉換爲SQL Server中的字符串。所有數據從XML到節點的路徑
所以假設我有這樣的XML:
<node1>
<node2>
<node3 att1="1">
456
</node3>
<node4 att2="25"/>
</node2>
</node1>
我要的是得到這樣的數據:
╔══════════════════════════╦════════════╗
║ Name ║ Value ║
╠══════════════════════════╬════════════╣
║ node1/node2/node3 ║ 456 ║
║ node1/node2/node3/@att1 ║ 1 ║
║ node1/node2/node3/@att2 ║ 25 ║
╚══════════════════════════╩════════════╝
我不記得了XPath的不夠好,我可以做到這一點遞歸查詢(SQL FIDDLE):
declare @data xml
set @data = '<root><node2><node3 att1="1">ggf</node3><node4 att2="25"/></node2></root>'
;with
CTE_xpath as (
select
T.C.value('local-name(.)', 'nvarchar(max)') as Name,
T.C.query('./*') as elements,
T.C.value('text()[1]', 'nvarchar(max)') as Value
from @data.nodes('*') as T(c)
union all
select
p.Name + '/' + T.C.value('local-name(.)', 'nvarchar(max)') as Name,
T.C.query('./*') as elements,
T.C.value('text()[1]', 'nvarchar(max)') as Value
from CTE_xpath as p
cross apply p.elements.nodes('*') as T(C)
union all
select
p.Name + '/' +
T.C.value('local-name(..)', 'nvarchar(max)') + '/@' +
T.C.value('local-name(.)', 'nvarchar(max)') as Name,
null as elements,
T.C.value('.', 'nvarchar(max)') as Value
from CTE_xpath as p
cross apply p.elements.nodes('*/@*') as T(C)
)
select Name, Value
from CTE_xpath
where Value is not null
你怎麼想,什麼是做這個塔斯的最佳方式K +
Xpath將選擇節點好吧,它不會返回你的名字。你爲什麼在SQL中做這個?這可能是有用的http://stackoverflow.com/questions/14747762/convert-xml-to-key-value-pair-notation –
以及它只是一個有趣的問題:)。當我想以某種方式處理數據時,SQL對於我來說是第一語言。 感謝您的鏈接 –
我對好奇心沒有任何問題,並且總是很高興爲您的弓另一個字符串,但它不會是我的第一個選擇。 –