Please turn on JavaScript. To find out how to do this visit the WebWise JavaScript guide.

Overview

Transversing XML elements using W3 methods can be a real pain, however NodeLists can be constructed from XML documents meaning CSS selectors and filters can be used.

Creating an XML NodeList

The most common way of getting XML is from an glow.net HTTP request.

To create an XML NodeList, just pass the XML into glow.dom.get.

glow.net.get("data.xml", {
  onLoad: function(response) {
    var xmlNodeList = glow.dom.get( response.xml() );
  }
});

Filtering XML Data

Once you have your XML data, you can use CSS selectors and filters to get the data you want. Imagine the following in data.xml

<schedule>
  <programme programme_id="crid://bbc.co.uk/272898301" title="Breakfast">
    <synopsis>...</synopsis>
    <channel_id>BBCOne</channel_id>
    <start>2008-03-20T06:00:00Z</start>
    <duration>03:15:00</duration>
  </programme>
  <programme programme_id="crid://bbc.co.uk/272898302" title="To Buy or Not to Buy">
    <synopsis>...</synopsis>
    <channel_id>BBCTwo</channel_id>
    <start>2008-03-20T09:15:00Z</start>
    <duration>00:45:00</duration>
  </programme>
</schedule>

If you wanted to get all the programme nodes from BBCOne, you could do:

glow.net.get("data.xml", {
  onLoad: function(response) {
    var xmlNodeList = glow.dom.get( response.xml() );
    var channelNodes = xmlNodeList.get("channel_id");
    channelNodes = channelNodes.filter(function() {
      return glow.dom.get(this).text() == "BBCOne";
    });
    var bbcOneProgrammes = channelNodes.parent();
  }
});

In the above, we get all the "channel_id" elements, then filter the ones which contain the text "BBCOne", then we call parent() to get the parent "programme" element.

The code above could chained together to use less intermediate variables:

glow.net.get("data.xml", {
  onLoad: function(response) {
    var bbcOneProgrammes = glow.dom.get( response.xml() ).get("channel_id").filter(function() {
      return glow.dom.get(this).text() == "BBCOne";
    }).parent();
  }
});

BBC © 2014 The BBC is not responsible for the content of external sites. Read more.

This page is best viewed in an up-to-date web browser with style sheets (CSS) enabled. While you will be able to view the content of this page in your current browser, you will not be able to get the full visual experience. Please consider upgrading your browser software or enabling style sheets (CSS) if you are able to do so.