1

How can I declare the namespaces in a query?

I get an error when declaring the namespaces

Declare @Mydoc xml
set @Mydoc = (
         select importe, algo,XD,
               (select impuesto,tasa,transferencia
                from CfdiDet
                for xml raw('cfdi_detalle'),type)
         from cfdienc
         for xml raw('cfdi_encabezado'),type)

This is the part where I have a problem

set @Mydoc.modify('declare xmlnamespaces ('uri',cfdi')

I want to replace the "_" with ":"

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

The namespace prefixes are not just a part of string you could manipulate with a .modify()... Well, you could convert the XML to string, do a REPLACE and convert it back to XML. But the proper way is to declare the namespace.

To declare a namespace you can either use WITH XMLNAMESPACES or use an implicit namespace declaration (not possible in your case).

Try this

DECLARE @Mydoc XML;

WITH XMLNAMESPACES('uri' AS cfdi)
SELECT @Mydoc=
(
SELECT 'SomeDummy' AS importe
FOR XML RAW('cfdi:encabezado'),TYPE
);

SELECT @Mydoc 

The result

<cfdi:encabezado xmlns:cfdi="uri" importe="SomeDummy" />
Shnugo
  • 66,100
  • 9
  • 53
  • 114
  • do you happen to know how I'm doing the encoding = "uft-8" to my file? is that it is only generated in version = "1.0" and now ... – carlitus212 Nov 30 '17 at 04:41
  • you are my hero!! :D – carlitus212 Nov 30 '17 at 04:42
  • @carlitus212 The XML declaration `` is not really bound to the XML. This is something which tells a consumer details about the content and it's encoding. There is absolutely no sense in writing something like `utf-8` into the header, if the real encoding is `UCS-2`. This declaration is not just some fancy magic... When you write your XML to a file, you should set the proper encoding and state this in the header. This **is not supported** natively. [Read this related question](https://stackoverflow.com/q/37439159/5089204) – Shnugo Nov 30 '17 at 09:59
  • Thank you very much, you helped me a lot :D – carlitus212 Nov 30 '17 at 15:31
  • hello friend, I wanted to see if you could just help me one more time, how could replace the "cfdi_" with "cfdi:" without using a namespaces since it duplicates for each node and does not work for me – carlitus212 Dec 01 '17 at 20:18
  • 1
    @carlitus212 just use something like `REPLACE(CAST(YourXml AS NVARCHAR(MAX)),'cfdi_','cfdi:')`. And use another `REPLACE()` or `STUFF()` to set the namespace declaration into the root node manually. – Shnugo Dec 03 '17 at 15:45