Reading XML in SQL Server with default and custom namespace

To read the XML document in SQL which contains the Name Spaces (default and custom) follow the below mentioned steps

1) Declare a variable of XML data type and assign the XML data to it.
2) Note down the list of name spaces used in XML document which need to be registered while extracting data.
3) Defined name spaces using “:with xmlnamespaces” to extract the data contains the name spaces.
4) Use the “value” and “nodes” on XML document object to extract the data. SQL example:

Declare @xmlOut xml
Set @xmlOut = 
'<xbrl xmlns="http://www.default.com/xmldata" xmlns:test="http://www.test.com/test">
  <Method1Response>
   <test:Method1Result>Element Data</test:Method1Result>
  </Method1Response>
</xbrl>'

declare @xDoc as xml
set @xDoc = cast(@xmlOut as xml)

declare @hdoc int
exec sp_xml_preparedocument @hdoc OUTPUT, @xDoc

;with xmlnamespaces('http://www.default.com/xmldata' as [default], 'http://www.test.com/test' as test)
select T.N.value('.', 'nvarchar(max)') As Data
from @xDoc.nodes('/default:xbrl/default:Method1Response/test:Method1Result') as T(N)


NameSpaces
Advertisements

#read-xml-with-sql