Travis Pettijohn: Blog

OPENXML and sp_xml_preparedocument with Namespaces

Posting this for mainly my reference, as the SQL Server documentation is a bit slim. When your XML has namespaces, sp_xml_preparedocument and OPENXML have to be used differently. The bold text below highlights the gotchas.

DECLARE @Errors	nvarchar(2000)
SET @Errors = '<Errors xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Error xmlns="http://tempuri.org/Foo.xsd">
    <Code>-1</Code>
    <UniqueName>InvalidFormat</UniqueName>
    <Warning>false</Warning>
  </Error>
  <Error xmlns="http://tempuri.org/Foo.xsd">
    <Code>-1</Code>
    <UniqueName>MaxLength</UniqueName>
    <Warning>false</Warning>
  </Error>
</Errors>'

SELECT @Errors

DECLARE @x_handle int
exec sp_xml_preparedocument @x_handle OUTPUT, @Errors, '<root xmlns:x="http://tempuri.org/Foo.xsd"/>'

SELECT * 
FROM OPENXML(@x_handle, '/Errors/x:Error', 2)
	WITH (UniqueName nvarchar(50) 'x:UniqueName', Warning nvarchar(5) 'x:Warning') XmlErrors

exec sp_xml_removedocument @x_handle