Author Posts

January 1, 2012 at 12:00 am

by yooakim at 2012-08-15 01:20:27

I am Learning PowerShell and love it more by every day. It's simple and elegant! And I love the object pipeline, it makes stitching things togehter childs play (almost!)

I have a question about using the Invoke-Rest method. I use it against a RSS feed. This particular RSS feed wraps the contents of title, description and other elements in < ![CDATA[Här är texten med lite specialare]]

When I use this code

Invoke-RestMethod $url

Everything works but the result does not give me the content of the CDATA elements. I know I can use .innerText on these elements but am wondering if there is Another, easier, way to do this?

Any suggestions of how to obtain content of CDATA elements?

Cheers,
Joakim

by DougFinke at 2012-08-15 12:14:02

Hi Joakim and thanks for the post.

You should be able to get the content of the CDATA section this way.

(Invoke-RestMethod $url).Title.InnerText

Here's the challenge, if the Title does not contain a CDATA section, this will print nothing.

So, you'll need to foreach over the results and check and either print the Title or Title.InnerText.

Post the RSS feed url and we can take a look.

Thanks
Doug

by yooakim at 2012-08-15 22:24:58

Thanks, this is the URL I'm reading from:

http://sverigesradio.se/api/rss/pod/4023

I'm not sure why the keep encoding everything in CDATA since it is UTF-8 but they do... 😉

/j

by DougFinke at 2012-08-16 04:31:26

Yes, many sites do things differently with their feeds. The good news is, PowerShell is flexible enough so you don't hit too many walls. Below are a couple ways you could process that feed. From a quick look, it seems they are all wrapped in CDATA sections.

Invoke-RestMethod http://sverigesradio.se/api/rss/pod/4023 |
Select Pubdate, Author, @{Name='Title'; Expression={$_.Title.InnerText}}

Invoke-RestMethod http://sverigesradio.se/api/rss/pod/4023 | ForEach {
[PSCustomObject] @{
Pubdate = $_.pubdate
Title = $_.Title.InnerText
Author = $_.Author
}
}

by yooakim at 2012-08-16 04:59:32

With PowerShell v3.0 it's so elegant! Thanks 🙂

/joakim