I have duplicate child elements in my RSS feed. Won't parse it in JavaScript

67 Views Asked by At

I'm pulling RSS data from this URL and this is how their data structure looks like.

<item>
<itunes:episodeType>full</itunes:episodeType>
<itunes:season>6</itunes:season>
<itunes:episode>49</itunes:episode>
<itunes:season>6</itunes:season>
</item>

It has duplicate child element itunes:season. How do I correctly parse it in JavaSCript? Any help will be apprciated! :)

here is the gist of my code:

success: function(data) {
   .find("item")
     .each(function() {
       const el = $(this);
       const seasonLS = el.find("itunes\\:season").text();
       const episodeLS = el.find("itunes\\:episode").text();  
    };

I tried fetching it by the child name but the duplicate child names are throwing it off.

Edit:

Sorry for the unclear question. Here is more information.

  1. The expected output for <itunes:season> is 6. This one spits out 66.

  2. .find() is chained on below:

const RSS_URL = *** URL ***;

$.ajax(RSS_URL, {
  accepts: {
     xml: "application/rss+xml"
  },
  dataType: "xml",
  success: function(data) {
    console.log(data)
    $(data)
      .find("item")...
1

There are 1 best solutions below

0
Zak On BEST ANSWER

If your goal is to just grab those two elements regardless of how many there are .. Why not just create a DOM object, and search by tag .. Then find the first index of each:

const htmlString = `<item>
<itunes:episodeType>full</itunes:episodeType>
<itunes:season>6</itunes:season>
<itunes:episode>49</itunes:episode>
<itunes:season>6</itunes:season>
</item>
<item>
<itunes:episodeType>full</itunes:episodeType>
<itunes:season>7</itunes:season>
<itunes:episode>55</itunes:episode>
<itunes:season>5</itunes:season>
</item>`;

const domParser = new DOMParser();
const docElement = domParser.parseFromString(htmlString, "text/html").documentElement;

var emCollection = docElement.getElementsByTagName("item");
for (var i = 0; i < emCollection.length; i++) {
  const seasonLS = emCollection[i].getElementsByTagName('itunes:season')[0].innerHTML;
  const episodeLS = emCollection[i].getElementsByTagName('itunes:episode')[0].innerHTML;
  console.log("Episode: " + episodeLS + "\n Season: " + seasonLS)
}