Unable to read content when XML has 2 wrappers

This code works great when removing a shell <data>from XML and nodes, but when you add it as shown below, I get 0 results.

  -- Declare XML variable
  DECLARE @data XML;

  -- Element-centered XML
  SET @data =
  N'
  <data xmlns="test.xsd">
    <subdata>
      <customer>
        <id>1</id>
        <name>Allied Industries</name>
      </customer>
      <customer>
        <id>2</id>
        <name>Trades International</name>
      </customer>
    </subdata>
  </data>';

  -- Using the query() method
  SELECT T.customer.query('id').value('.', 'INT') AS customer_id,
         T.customer.query('name').value('.', 'VARCHAR(20)') AS customer_name
  FROM @data.nodes('data/subdata/customer') AS T(customer);

But it works fine when I do it like this:

  -- Element-centered XML
  SET @data =
  N'
    <subdata>
      <customer>
        <id>1</id>
        <name>Allied Industries</name>
      </customer>
      <customer>
        <id>2</id>
        <name>Trades International</name>
      </customer>
    </subdata>
 ';

  -- Using the query() method
  SELECT T.customer.query('id').value('.', 'INT') AS customer_id,
         T.customer.query('name').value('.', 'VARCHAR(20)') AS customer_name
  FROM @data.nodes('subdata/customer') AS T(customer);

Does anyone know how and why I do not get the results in the first example when the parent shell exists <data>?

+3
source share
1 answer

The problem has nothing to do with the number of wrappers around your XML data. The problem is this: your first sample defines the XML ( xmlns="test.xsd") namespace in <data>node, but your request does not honor this.

:

-- Using the query() method
;WITH XMLNAMESPACES (DEFAULT 'test.xsd')
SELECT 
    T.customer.query('id').value('.', 'INT') AS customer_id,
    T.customer.query('name').value('.', 'VARCHAR(20)') AS customer_name
FROM 
    @data.nodes('data/subdata/customer') AS T(customer);

....

XML - .

+6

All Articles