0

I'm trying to parse out the following XML with TSQL:

<Response xmlns="http://data.fcc.gov/api" status="OK" executionTime="9">
    <Block FIPS="181770103002004" />
    <County FIPS="18177" name="Wayne" />
    <State FIPS="18" code="IN" name="Indiana" />
</Response>

Using the following script:

SELECT x.i.value('@name', 'varchar(200)') AS county
FROM @xml.nodes('Response/County') AS x(i)

But I get no results, any help as to what I'm doing wrong would be greatly appreciated.

Thanks!

2 Answers 2

4

Your XML namespace is messing things up. Either remove the xmlns="http://data.fcc.gov/api" from the Response element, or prefix your query with WITH XMLNAMESPACES ( DEFAULT 'http://data.fcc.gov/api')

;WITH XMLNAMESPACES ( DEFAULT 'http://data.fcc.gov/api')
SELECT x.i.value('@name', 'varchar(200)') AS county
FROM @xml.nodes('Response/County') AS x(i)

Or you can use wildcard namespaces in the query:

SELECT x.i.value('@name', 'varchar(200)') AS county
FROM @xml.nodes('*:Response/*:County') AS x(i)
Sign up to request clarification or add additional context in comments.

1 Comment

Right on the nose. Both of those suggestions worked. I ended up removing the xmlns element and my script worked. Thanks for the quick reply.
0

You can do it using OPENXML like this:

DECLARE @idoc INT
DECLARE @xml AS XML  = 

'<Response xmlns="http://data.fcc.gov/api" status="OK" executionTime="9">
    <Block FIPS="181770103002004" />
    <County FIPS="18177" name="Wayne" />
    <State FIPS="18" code="IN" name="Indiana" />
</Response>'

EXEC sp_xml_preparedocument @idoc OUTPUT, @xml, N'<root xmlns:n="http://data.fcc.gov/api" />'

SELECT
    Name AS County
FROM OPENXML (@idoc, '/n:Response/n:County', 1)
WITH
    (
        Name VARCHAR(255) '@name'
    )

EXEC sp_xml_removedocument @idoc
GO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.