简体   繁体   中英

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.

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, eg:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM