I need to select some columns from a table as XML with the included namespaces along with the other columns as they are. For example, I have the following table layout:
ID C1 X1C1 X1C2 X2C3
1 A 1 2 3
Refund request:
ID C1 XmlData
1 A <xmldata1>
2 A <xmldata2>
Where <xmldata1>will be:
<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>
and <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>
I have a good link on how to build xml from this SO question , but I cannot put namespaces. If possible, how to do it?
Edit: I used the following query trying to get the desired result: select 1 ID, 'A' C1, 1 X1C1, 2 X1C2, 3 X2C3 in #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
drop table
Here is the result of its xml part:
<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>
I cannot get rid of namespaces in Childnode.