I am sure that you understand that additional namespace declarations do not change the meaning of the XML document, therefore, if the result is consumed using an XML-compatible tool, they should not matter. However, I know that there are some tools that do not have the correct XML namespace, and in a large XML instance, redundant repeated namespace declarations can greatly inflate the size of the result, which can cause its own problems.
In general, one canβt get around the fact that each SELECT...FOR XML within the WITH XMLNAMESPACES prefix generates namespace declarations on an external XML element in its result set in all XML-supported versions of SQL Server prior to SQL Server 2012.
In your specific example, you can approach the desired XML by separating SELECT rather than overlaying them, and using the ROOT syntax for the wrapping root element, this way:
DECLARE @inner XML; WITH XMLNAMESPACES('http://www.google.com/schemas/sitemap-image/1.1' as [image]) SELECT @inner = ( SELECT 'anotherloc' AS [image:loc] FOR XML PATH('image:image'), TYPE ) ;WITH XMLNAMESPACES( DEFAULT 'http://www.sitemaps.org/schemas/sitemap/0.9' ) SELECT 'mysite' AS [loc], @inner FOR XML PATH('url'), ROOT('urlset'), TYPE
Result:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>mysite</loc> <image:image xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns=""> <image:loc>anotherloc</image:loc> </image:image> </url> </urlset>
But this approach does not provide a completely general solution to the problem.
Chris dickson
source share