'Generating xml with SQL Server with child namespace

I am generating an XML using SQL Server and I need the following name space:

xmlns:ns0="http://www.w3.org/2001/XMLSchema-instance" ns0:noNamespaceSchemaLocation="http://myLink2Schema.xsd"

I am trying to generate it with the following code:

WITH XMLNAMESPACES( 

 'http://www.w3.org/2001/XMLSchema-instance' as ns0
 ,'http://myLink2Schema.xsd' as noNamespaceSchemaLocation
)

But the result I get is:

xmlns:noNamespaceSchemaLocation="http://myLink2Schema.xsd" xmlns:ns0="http://www.w3.org/2001/XMLSchema-instance"

If I try to write it like this it does not work:

WITH XMLNAMESPACES( 

 'http://www.w3.org/2001/XMLSchema-instance' as ns0
 ,'http://myLink2Schema.xsd' as ns0:noNamespaceSchemaLocation
)

It is like noNamespaceSchemaLocation needs to be a child of ns0.

I know I could treat the XML like a string and manipulate it after the generation but I'd rather do it in the right way.



Solution 1:[1]

In what you've specified as a "need" ns0:noNamespaceSchemaLocation="http://myLink2Schema.xsd" is not a namespace definition but an attribute in the ns0 namespace prefix. You output that as part of your SQL query, e.g.:

with xmlnamespaces (
'http://www.w3.org/2001/XMLSchema-instance' as ns0
)
select
    'http://myLink2Schema.xsd' as [@ns0:noNamespaceSchemaLocation],
    1 as World
for xml path('Hello');

Which outputs:

<Hello xmlns:ns0="http://www.w3.org/2001/XMLSchema-instance" ns0:noNamespaceSchemaLocation="http://myLink2Schema.xsd">
  <World>1</World>
</Hello>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AlwaysLearning