我正在尝试将 xml 中的所有数据转换为 SQL Server 中的字符串。
所以假设我有这样的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
您如何看待,完成这项任务的最佳方法是什么?