Reputation: 75
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. :)
Upvotes: 0
Views: 24
Reputation: 318172
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);
}
Upvotes: 1