0

I have an XML file, "Fixtures", and I am trying to get all of the fixtures within the "irelandGames" section. I can go through and 'manually' select the fixtures, but surely there is a better way, rather than me having to actually know the exact position of every item in the file.

Here is the XML file:

<?xml version="1.0" encoding="utf-8" ?>

<fixtures>
  <irelandGames>
    <md1>
      <date>13</date>
      <time>17</time>
      <location>Stade de France</location>
      <teams>Ireland V Sweden</teams>
    </md1>
    <md2>
      <date>18</date>
      <time>14</time>
      <location>Stade de Bordeaux</location>
      <teams>Belgium V Ireland</teams>
    </md2>
    <md3>
      <date>22</date>
      <time>20</time>
      <location>Stade Pierre Mauroy</location>
      <teams>Italy V Ireland</teams>
    </md3>
  </irelandGames>

<italyGames>
    <md1>
      <date>13</date>
      <time>20</time>
      <location>Stade de Lyon</location>
      <teams>Belgium v Italy</teams>
    </md1>
    <md2>
      <date>17</date>
      <time>14</time>
      <location>Stade de Toulouse</location>
      <teams>Italy V Sweden</teams>
    </md2>
  <md3>
      <date>22</date>
      <time>20</time>
      <location>Stade Pierre Mauroy</location>
      <teams>Italy V Ireland</teams>
    </md3>
  </italyGames>
</fixtures>

Here is the code I've used to retrieve Ireland fixtures:

var xmlDoc = xhttp.responseXML;
var x = xmlDoc.getElementsByTagName("teams");
console.log("x: " + x.length);

var i;
for (i = 0; i < 3; i++)
{
    irelandMatches.push(x[i].childNodes[0].nodeValue);
}

As you can see, for me to get Italy's fixtures, I could code it get "teams" 3 to 5, however, this seems very messy. Is there a way to get it to retrieve all "teams" from, like "irelandGames" rather than having to number each node.

Thanks. :)

1 Answer 1

1

You can just target the tags for the countries before you get the teams

var xmlDoc = xhttp.responseXML;

var country = xmlDoc.getElementsByTagName("irelandGames");
var teams   = country[0].getElementsByTagName("teams");

var irelandMatches = [];

for (var i=0; i<teams.length; i++) {
    irelandMatches.push(teams[i].childNodes[0].nodeValue);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting this error: "TypeError: country.getElementsByTagName is not a function" - any suggestions? :)
Yes, use country[0].getElementsByTagName("teams")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.