简体   繁体   中英

Parsing XML using TSQL

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM