Tesla Tesla - 5 months ago 16
SQL Question

Unable to Parse XML using Sp_XML_Prepare document when namespaces are present

I have an XML with namespaces. I am unable to parse it using sp_xml_preparedocument. I am able to parse if name spaces are removed from XML. Also I tried passing name spaces to Sp as parameter. But it is not returning any result.
Below is the Namespaces node.

'<SyncPurchaseOrder
xmlns="http://schema.inf.com/infOAGIS/2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://schema.inf.com/infOAGIS/2 http://schema.inf.com/2.10.0/infOAGIS/BODs/Developer/SyncPurchaseOrder.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
releaseID="9.2"
versionID="2.10.0"
/>'


Thanks in Advance.

Answer

Reading an XML with sp_xml_preparedocument is out-dated and should be replaced by the appropriate XPath-methods!

From your question I assume, that the real XML is bigger. This will only retrieve the releaseID to show the how-to-do...

Try it like this:

DECLARE @x XML=
'<SyncPurchaseOrder 
xmlns="http://schema.inf.com/infOAGIS/2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://schema.inf.com/infOAGIS/2 http://schema.inf.com/2.10.0/infOAGIS/BODs/Developer/SyncPurchaseOrder.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
releaseID="9.2"
versionID="2.10.0"
/>';

WITH XMLNAMESPACES(DEFAULT 'http://schema.inf.com/infOAGIS/2'
                  ,'http://www.w3.org/2001/XMLSchema-instance' AS xsi
                  ,'http://schema.inf.com/infOAGIS/2 http://schema.inf.com/2.10.0/infOAGIS/BODs/Developer/SyncPurchaseOrder.xsd' AS xsd)
SELECT @x.value('(/SyncPurchaseOrder/@releaseID)[1]','varchar(max)') AS releaseID

Another way to get away without the namespaces was a wildcard:

SELECT @x.value('/*:SyncPurchaseOrder[1]/@releaseID','varchar(max)') AS releaseID