简体   繁体   中英

How to convert text to XML when text contains xml namespace?

On trying to phrase a different question on here... how to query the xml below, I found I could not successfully convert it to XML to pose the question.

Below is my attempt

;WITH CTE AS
( SELECT CONVERT(XML,N'
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://www.opengis.net/kml/2.2' xmlns:gx='http://www.google.com/kml/ext/2.2'>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                <altitudeMode>clampToGround</altitudeMode>
                <when>2017-10-26T11:42:05Z</when>
                <gx:coord>Lat Long Altitude</gx:coord>
                <when>2017-10-26T11:41:40Z</when>
                <gx:coord>Lat Long Altitude</gx:coord>
            </gx:Track>
        </Placemark>
    </Document>
</kml>'
        ) AS BulkColumnXML
)
SELECT *
FROM CTE

The error is:

Msg 9438, Level 16, State 1, Line 16

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

I'm not sure what I'm doing wrong, if I remove the namespace declaration the conversion works fine.

Correct Code:

;WITH CTE AS
( SELECT CONVERT(XML,'<?xml version=''1.0'' encoding=''UTF-8''?>
<kml xmlns=''http://www.opengis.net/kml/2.2'' xmlns:gx=''http://www.google.com/kml/ext/2.2''>
    <Document>
        <Placemark>
            <open>1</open>
            <gx:Track>
                <altitudeMode>clampToGround</altitudeMode>
                <when>2017-10-26T11:42:05Z</when>
                <gx:coord>Lat Long Altitude</gx:coord>
                <when>2017-10-26T11:41:40Z</when>
                <gx:coord>Lat Long Altitude</gx:coord>
            </gx:Track>
        </Placemark>
    </Document>
</kml>'
        ) AS BulkColumnXML
)
SELECT *
FROM CTE

Looks like you have whitespace before your XML prolog. Reformat the CTE as follows:

;WITH CTE AS
( SELECT CONVERT(XML, 
N'<?xml version="1.0" encoding="UTF-8"?>
           . . . 

A plain XML can have whitespace before the root element, but there must be no data before the XML Prolog.

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