Limit xml-namespaces to only the main root

左心房为你撑大大i 提交于 2019-12-23 22:08:31

问题


I have this query

 WITH XMLNAMESPACES(DEFAULT 'https://tribunet.hacienda.go.cr /docs/esquemas/2017/v4.2/facturaElectronica'
                      ,'http://www.w3.org/2001/XMLSchema' AS xsd
                      ,'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT 1 AS [id]
        ,0 AS [pass]
        (
         /*Others*/
        SELECT 
        OT.OTH_MESSAGE as Others
        FROM [crdx_COREDev1].[dbo].[OTH_OTHERS] as OT
        where 
        OT.OTH_ID=E.OTH_ID
        fOR XML PATH ('Others'), type

       )
      ,0 AS [CONSECUTIVE]

      FOR XML PATH('FE');

This generates this XML

<FE xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns="https://tribunet.hacienda.go.cr/docs/esquemas/2017/v4.2    /facturaElectronica"> <- CHANGE 2
 <id>1</id>
 <pass>0</pass>
 <CONSECUTIVE>0</CONSECUTIVE>
 <Others xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns="https://tribunet.hacienda.go.cr/docs/esquemas/2017/v4.2 /facturaElectronica">
 <MESSAGE>MESSAGE</MESSAGE>       
</Others> 
 </FE>

Now my question: I would like only <FE> to show the namespaces, but - as you see in the xml - that declarations appear also in <Others>. How can I limit this to <FE>?


回答1:


This is an annoying and well known issue and occurs whenever you use namespaces in connection with nested sub-queries in FOR XML queries...

There has been a connect issue for more than 10 years - until it disappaered recently.

It is important to mention, that these repeated namespace declarations are not wrong, just bloating your XML. And it can collide with (to) strict schema validations.

No good solution, just workarounds:

  • Create the inner XML without the namespace and add the wrapping node on string base, or
  • Create the namespaces as normal attributes (but not named xmlns) and use REPLACE to change the names.

Both workarounds need a conversion to NVARCHAR(MAX) and back to XML.

I really have no idea, why this was implemented this way...

Find some related examples

  • here
  • and here
  • and here
  • and here

Attention:

xmlns="https://tribunet.hacienda.go.cr/docs/esquemas/2017/v4.2    /facturaElectronica">

You are using namespace URLs with blanks. This is not allowed...



来源:https://stackoverflow.com/questions/49653985/limit-xml-namespaces-to-only-the-main-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!