GetXPath

From SoftIVR

Jump to: navigation, search

getXPath

getXPath(path) extracts an element from an XML structure previously parsed using parseXML.

Parameters

  • path - the path to the element

Return value

The value of that element.

Example

The weather report sample application querys data from Yahoo's weather feed. A simplified version of the XML returned by a call to Yahoo's API is:

<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
  <channel>
    <item>
      <title>Conditions for Breckenridge, CO at 1:53 am MST</title>
      <geo:lat>39.48</geo:lat>
      <geo:long>-106.04</geo:long>
      <link>http://us.rd.yahoo.com/dailynews/rss/weather/Breckenridge__CO/*http://weather.yahoo.com/forecast/80424_f.html</link>
      <pubDate>Mon, 15 Dec 2008 1:53 am MST</pubDate>
      <yweather:condition  text="Fair"  code="33"  temp="-14"  date="Mon, 15 Dec 2008 1:53 am MST" />
      <yweather:forecast day="Mon" date="15 Dec 2008" low="8" high="13" text="Snow Showers" code="14" />
      <yweather:forecast day="Tue" date="16 Dec 2008" low="-4" high="13" text="Snow Showers" code="14" />
    </item>
  </channel>
</rss>

Having parsed this structure, the sample application extracts specific information as follows:

say(getXPath("/channel/item/title") + ".");
say("Conditions are " + getXPath("/channel/item/yweather:condition/text") + ".");
say("It is " + getXPath("/channel/item/yweather:condition/temp") + " fahrenheit.");

to read the title, the weather conditions and the temperature back to the caller.

In instances where there are more than one instance of an element, for example:

<test>
  <item>
    <title>Item 1</title>
  </item>
  <item>
    <title>Item 2</title>
  </item>
</test>

the path can contain elements with subscripts. In this instance:

log(getXPath("item[0]/title/content"));
log(getXPath("item[1]/title/content"));

would log the two titles. item/title/content would refer to the first title in the list; in the situation where there is only one item, item[0]/title/content is a valid path.

Return to Javascript functions.

Personal tools