views:

15

answers:

1

For background see this question:

http://stackoverflow.com/questions/1415003/sql-server-xml-data-type-query-issue

I'm trying to query against an XML object in SQL Server 2005. The query works fine when there's no namespace defined in the XML. However, when the namespace element is there I cannot seem to get the value for a node element. Here's an example:

DECLARE @xmlWithNameSpace XML
DECLARE @xmlWithoutNameSpace XML

SET @xmlWithNameSpace = '<?xml version="1.0" encoding="UTF-8"?>
    <Feed xmlns="gizmo">
        <Product id="4444">
            <ProductId>4444</ProductId>
        </Product>
    </Feed>'

SET @xmlWithoutNameSpace = '<?xml version="1.0" encoding="UTF-8"?>
    <Feed>
        <Product id="4444">
            <ProductId>4444</ProductId>
        </Product>
    </Feed>'

SELECT feed.product.value('@id[1]', 'INT') AS productId  
FROM @xmlWithNameSpace.nodes('declare namespace ns="gizmo"; /ns:Feed/ns:Product') feed(product)

UNION ALL

SELECT feed.product.value('ProductId[1]', 'INT') AS productId  
FROM @xmlWithNameSpace.nodes('declare namespace ns="gizmo"; /ns:Feed/ns:Product') feed(product)

UNION ALL

SELECT feed.product.value('@id[1]', 'INT') AS productId 
FROM @xmlWithoutNameSpace.nodes('/Feed/Product') feed(product)

UNION ALL

SELECT feed.product.value('ProductId[1]', 'INT') AS productId 
FROM @xmlWithoutNameSpace.nodes('/Feed/Product') feed(product)

This returns

4444  
NULL  
4444  
4444

What am I doing wrong to get the value of the ProductId node (4444) when the namespace is in use?

Thanks in advance for any guidance.

A: 

The answer is I have to define the node element I'm trying to access with the namespece as well. All of these samples return 4444 as expected:

WITH XMLNAMESPACES ('gizmo' AS nsWithXNS)

SELECT feed.product.value('@id[1]', 'INT') AS productId 
FROM @xmlWithNameSpace.nodes('/nsWithXNS:Feed/nsWithXNS:Product') feed(product)

UNION ALL

SELECT feed.product.value('nsWithXNS:ProductId[1]', 'INT') AS productId 
FROM @xmlWithNameSpace.nodes('/nsWithXNS:Feed/nsWithXNS:Product') feed(product)

UNION ALL

SELECT feed.product.value('@id[1]', 'INT') AS productId 
FROM @xmlWithNameSpace.nodes('declare namespace ns="gizmo"; /ns:Feed/ns:Product') feed(product)

UNION ALL

SELECT feed.product.value('declare namespace ns="gizmo"; ns:ProductId[1]', 'INT') AS productId 
FROM @xmlWithNameSpace.nodes('declare namespace ns="gizmo"; /ns:Feed/ns:Product') feed(product)

Thanks for reading and I hope this helps someone else.

hoi polloi