6

I am unsure how to get the value of dc:creator from an RSS-feed using SQL. This is my xml/rss-feed:

<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
  <title>Foobar RSS</title>
  <link>http://www.foobar.com/</link>
  <description>RSS feed</description>
  <language>en</language>
  <ttl>15</ttl>
    <item>
        <title>This is my title</title>
        <link>http://www.foobar.com/link/blabla</link>
        <description>Bla..bla..bla..</description>
        <dc:creator>John Doe</dc:creator>
        <guid isPermaLink="false">00082EA751F1D905DE00E7CFA2417DA9</guid>
        <pubDate>Wed, 26 Oct 2011 00:00:00 +0200</pubDate>
    </item>
</channel>
</rss>

In my SQL I use something like this to get the values - e.g for pubDate I use something like this:

DECLARE @xml XML
SET @xml = cast('my rss feed here' AS xml) 

SELECT
convert(datetime,substring(T.nref.value('pubDate[1]','nvarchar(100)'),6,20)) as pubdate,
FROM @xml.nodes('//item') AS T(nref)

This works fine, but when I am trying to get dc:creator value 'John Doe', the following just gives me an error:

SELECT
   T.nref.value('dc:creator','nvarchar(100)') as creator
FROM @xml.nodes('//item') AS T(nref)

   error: 
   XQuery [value()]: The name "dc" does not denote a namespace.

I need to be able to select multiple columns from the rss-feed. Can anybody provide a solution or direction to get the value of dc:creator?

I have another question - how would you construct the code if you are doing it in a sub select?

E.g. 
INSERT INTO RSSResults (ID, pubDate)
SELECT @ID, tbl.pubDate FROM (     

;WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc) 
    SELECT 
       RSS.Item.value('(dc:creator)[1]', 'nvarchar(100)') as pubDate
    FROM 
       @xml.nodes('/rss/channel/item') as RSS(Item)) AS tbl 

The code breaks at ";WITH XMLNAMESPACES". Is it possible to include the namespace directly in the statement somehow?

Sha
  • 2,185
  • 1
  • 36
  • 61

1 Answers1

11

Try something like this:

DECLARE @xml XML
SET @xml = cast('my rss feed here' AS xml) 

;WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc)
SELECT
    @xml.value('(rss/channel/item/dc:creator)[1]', 'nvarchar(100)')

If you need to catch multiple items - try this:

DECLARE @xml XML
SET @xml = cast('my rss feed here' AS xml) 

;WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc)
SELECT
    RSS.Item.value('(dc:creator)[1]', 'nvarchar(100)')
FROM
    @xml.nodes('/rss/channel/item') as RSS(Item)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459