【发布时间】:2014-06-11 09:13:21
【问题描述】:
我需要从表中选择一些列作为 XML,其中包含名称空间以及其他列。例如,我有以下表格布局:
ID C1 X1C1 X1C2 X2C3
1 A 1 2 3
查询应该返回的是:
ID C1 XmlData
1 A <xmldata1>
2 A <xmldata2>
<xmldata1> 的位置:
<Root xmlns:xsd="w3.org/2001/XMLSchema" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:mst="microsoft.com/wsdl/types/">
<Child attrib="C1">
<ChildValue xsi:type="xsd:integer">1</ChildNode>
</Child>
<Child attrib="C2">
<ChildNode xsi:type="xsd:integer">2</ChildNode>
</Child>
</Root>
而<xmldata2> 将是:
<Rootxmlns:xsd="w3.org/2001/XMLSchema" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:mst="microsoft.com/wsdl/types/">
<Child attrib="C3">
<ChildNode xsi:type="xsd:integer">3</ChildNode>
</Child>
</Root>
我对如何从this SO question 构建 xml 有很好的参考,但我无法放入命名空间。如果可以的话怎么办?
编辑: 我使用以下查询试图获得所需的结果: 选择 1 ID, 'A' C1, 1 X1C1, 2 X1C2, 3 X2C3 进入#t
;with xmlnamespaces('w3.org/2001/XMLSchema' as xsd, 'w3.org/2001/XMLSchema-instance' as xsi, 'microsoft.com/wsdl/types/' as mst)
select ID, C1, (select (SELECT 'C1' "@attrib", 'xsd:integer' "ChildValue/@xsi:type",t.X1C1 as 'ChildValue' FOR XML PATH('Child'), type),(SELECT 'C2' "@name", 'xsd:integer' "ChildValue/@xsi:type", t.X1C2 as 'ChildValue' FOR XML PATH('Child'), type) FOR XML PATH('Root'), type) as property_data
FROM #t t
drop table #t
这是其 xml 部分的输出:
<Root xmlns:mst="microsoft.com/wsdl/types/" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema">
<Child xmlns:mst="microsoft.com/wsdl/types/" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema" attrib="C1">
<ChildValue xsi:type="xsd:integer">1</ChildValue>
</Child>
<Child xmlns:mst="microsoft.com/wsdl/types/" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema" name="C2">
<ChildValue xsi:type="xsd:integer">2</ChildValue>
</Child>
</Root>
我无法摆脱 Child 节点中的命名空间。
【问题讨论】:
标签: sql xml tsql sql-server-2008-r2