简体   繁体   中英

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.

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

UPDATE

If you have to stick with the out-dated FROM OPENXML you might do this

SELECT @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"
/>'

EXEC sp_xml_preparedocument @hDoc OUTPUT
                           ,@XML
                           ,'<SyncPurchaseOrder xmlns:d="http://schema.inf.com/infOAGIS/2"/>' --name it "d" as "default", but can be any name

SELECT releaseID
FROM OPENXML(@hDoc, 'd:SyncPurchaseOrder')
WITH 
(
releaseID   [nvarchar](20)  './@releaseID'
)

EXEC sp_xml_removedocument @hDoc
GO

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