How to select a nested tag from a XML with querySelector? (querySelector, nested tags)

Viewed 18

For a little side-project I am fetching data from rss-feeds and need to select an image url in order to render the cover of a podcast in my application.

I am selecting the mp3, title and author in the fetched XML like this, which works fine.

const items = feed.querySelectorAll('item');
const feedItems = [...items].slice(0, 1).map((el) => ({
      mp3: el.querySelector('enclosure').getAttribute('url'),
      title: el.querySelector('title').innerHTML,
      author: el.querySelector('author').innerHTML,
    })); 

The image url is nested in the XML though and I am having troubles to select it with querySelector.

<image>
<link>https://erklaermir.simplecast.com</link>
<title>Erklär mir die Welt</title>
<url>https://image.simplecastcdn.com/images/8991e97a-2827-4ade-a709-e50208868f3f/59e8ae3d-526c-435b-8ab8-0b2da0fa12ba/3000x3000/1521828793artwork.jpg?aid=rss_feed</url>
</image>

The link to the complete feed. https://feeds.feedburner.com/erklaermir

Does somebody know how I can select the nested url-tag in this XML?

Thank you very much. :)

1 Answers

The <url> element is an element (like <link> and <title>) not an attribute (you have no attributes in your XML).

You get data from it the same way as you get data from the other elements.

… except you should be using textContent for all of them since you want the strings as strings not as serialised HTML (with any special characters potentially encoded as character references).

You don't have an <enclosure> element at all, so I've no idea what el.querySelector('enclosure') is supposed to be doing.

el.querySelector('url').textContent
Related