Domanda

I have a problem with XML queries in SQL Server. I usually run a query on a @XML variable to fetch data like this but in a certain statement it does not work.

This code works correctly

Declare @XML as XML = 
'
<ResponseData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Remain>12345654321.1234</Remain>
  <ErrorMsg />
</ResponseData>';
;

Select 
    F.value('Remain[1]','decimal(18,4)') as A,
    F.value('ErrorMsg[1]','varchar(100)') as B
FROM  @XML.nodes('ResponseData')Tbl(F);

but if I add a new row in the first of @XML it can0t parse and return following error

XML parsing: line 2, character 6, text/xmldecl not at the beginning of input

Declare @XML as XML = 
'
<?xml version="1.0" encoding="utf-16"?>
<ResponseData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Remain>12345654321.1234</Remain>
  <ErrorMsg />
</ResponseData>';
;

Select 
    F.value('Remain[1]','decimal(18,4)') as A,
    F.value('ErrorMsg[1]','varchar(100)') as B
FROM  @XML.nodes('ResponseData')Tbl(F);

The <?xml version="1.0" encoding="utf-16"?> added to the @XML variable.

thanks

È stato utile?

Soluzione

There can't be any characters between the start of the string and the <?xml

Just remove the line break.

If you want to use utf-16, you'll need to prefix the string with an N

Declare @XML as XML = N'<?xml version="1.0" encoding="utf-16"?>....
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top