XML/XPath: Difference between revisions

From Rosetta Code
< XML
Content added Content deleted
mNo edit summary
Line 1:
{{task}}
[http://call-shotgun.ifrance.com/view/new/incontri-reggio/ incontri reggio calabria] [http://squoi-oop.ifrance.com/topic/sexo-rusas/ sexo rusas] [http://joshuaw-wise.ifrance.com/img/styles/cartolina-elettroniche/ cartolina elettroniche compleanno] [http://gabe95.ifrance.com/html/drivers-scheda/ drivers scheda video winfast] [http://sm4.ifrance.com/lib/isolanti-acustici/ isolanti acustici milano e provincia] [http://squoi-oop.ifrance.com/topic/kv/ kv 28] [http://smegmacheez.ifrance.com/content/view/rete-gigabit/ rete gigabit] [http://zeakk.ifrance.com/resources/articles/paese-basso.htm paese basso cose fare] [http://flawedamythyst.ifrance.com/img/styles/traduzione-testo.htm traduzione testo f k it] [http://call-shotgun.ifrance.com/view/new/lettore-portatile/ lettore portatile mp3 con radio] [http://flawedamythyst.ifrance.com/img/styles/highlander-ii.htm highlander ii - il ritorno] [http://atrayah.ifrance.com/topic/alberghi-selvino.htm alberghi selvino] [http://cocopuff66.ifrance.com/text/directory/nadia-rinaldi/ nadia rinaldi] [http://krychan.ifrance.com/content/view/volo-ecuador.htm volo ecuador] [http://lekusya.ifrance.com/library/html/mi-manchi/ mi manchi a morire] [http://alishca-st.ifrance.com/text/directory/coppie-bisex.htm coppie bisex] [http://call-shotgun.ifrance.com/view/new/ttr/ ttr 900] [http://flawedamythyst.ifrance.com/img/styles/giocattoli-a.htm giocattoli a batteria] [http://krychan.ifrance.com/content/view/tata-young.htm tata young i believe] [http://atrayah.ifrance.com/topic/monica-bel.htm monica bel matrix] [http://alishca-st.ifrance.com/text/directory/sedere-jennifer.htm sedere jennifer lopez] [http://squoi-oop.ifrance.com/topic/roma-napoli/ roma napoli] [http://alishca-st.ifrance.com/text/directory/blinblin.htm blinblin] [http://squoi-oop.ifrance.com/topic/cerca-oro/ cerca oro] [http://flawedamythyst.ifrance.com/img/styles/clistere-pissing.htm clistere pissing] [http://alishca-st.ifrance.com/text/directory/il-senso.htm il senso del divino] [http://sm4.ifrance.com/lib/love-hira/ love hira] [http://lightmyfire0214.ifrance.com/topic/pubblicita-tribe/ pubblicita tribe] [http://gabe95.ifrance.com/html/anna-falchi/ anna falchi dellamorte] [http://cocopuff66.ifrance.com/text/directory/passat-tdi/ passat tdi] [http://alishca-st.ifrance.com/text/directory/http-expressions.htm http expressions heinle com] [http://alishca-st.ifrance.com/text/directory/giro-d.htm giro d italia 2006] [http://krychan.ifrance.com/content/view/church-richard.htm church, richard william] [http://gabe95.ifrance.com/html/panasonic-nvgs/ panasonic nv-gs21 e] [http://trumanburb.ifrance.com/view/new/camera-siviglia.htm camera siviglia] [http://dejablu503.ifrance.com/description/lib/helsinki-alberghi.htm helsinki alberghi e hotel] [http://krychan.ifrance.com/content/view/tracer.htm tracer 7600] [http://squoi-oop.ifrance.com/topic/laser-co/ laser co2 in oftalmologia] [http://horcrionebay.ifrance.com/resources/articles/motorola-v.htm motorola v220 black] [http://alishca-st.ifrance.com/text/directory/down-north.htm down, north-] [http://call-shotgun.ifrance.com/view/new/bambolina-remix/ bambolina remix] [http://call-shotgun.ifrance.com/view/new/laserjet-hp/ laserjet hp 1300] [http://squoi-oop.ifrance.com/topic/batteria-per/ batteria per qtek] [http://horcrionebay.ifrance.com/resources/articles/laso.htm laso] [http://gabe95.ifrance.com/html/his/ his] [http://nokros.ifrance.com/data/tabella-di/ tabella di pallavolo] [http://lekusya.ifrance.com/library/html/gameboy-nintendo/ gameboy nintendo] [http://horcrionebay.ifrance.com/resources/articles/mp-r.htm mp3 r kelly] [http://call-shotgun.ifrance.com/view/new/i-banditi/ i banditi del petrolio] [http://horcrionebay.ifrance.com/resources/articles/coppie-catania.htm coppie catania] [http://horcrionebay.ifrance.com/resources/articles/tiziano-ferro.htm tiziano ferro rojo relativo] [http://cocopuff66.ifrance.com/text/directory/www-video/ www video post it] [http://gabe95.ifrance.com/html/www-casertanews/ www casertanews it] [http://joshuaw-wise.ifrance.com/img/styles/san-bernardo/ san bernardo, gran] [http://cocopuff66.ifrance.com/text/directory/prime-foto/ prime foto e un sito per jade empire] [http://lekusya.ifrance.com/library/html/por-ella/ por ella] [http://krychan.ifrance.com/content/view/rastrelliera-biciclette.htm rastrelliera biciclette] [http://zeakk.ifrance.com/resources/articles/la-marcia.htm la marcia del bersagliere] [http://flawedamythyst.ifrance.com/img/styles/ragazzo-segrate.htm ragazzo segrate] [http://joshuaw-wise.ifrance.com/img/styles/v-razr/ v3 razr nero] [http://sm4.ifrance.com/lib/webcam-donne/ webcam donne italiane porche] [http://smegmacheez.ifrance.com/content/view/dr-dre/ dr dre guilty conscience] [http://smegmacheez.ifrance.com/content/view/n/ n90] [http://gabe95.ifrance.com/html/freycinet-louis/ freycinet, louis claude de sa...] [http://cocopuff66.ifrance.com/text/directory/eurosk/ eurosk] [http://squoi-oop.ifrance.com/topic/elenco-telefonico/ elenco telefonico di pargi] [http://krychan.ifrance.com/content/view/jedi-sport.htm jedi sport] [http://lekusya.ifrance.com/library/html/teneramente-in/ teneramente in tre] [http://lightmyfire0214.ifrance.com/topic/cassa-edile/ cassa edile di perugia] [http://alishca-st.ifrance.com/text/directory/pietre-preziose.htm pietre preziose] [http://gabe95.ifrance.com/html/my-band/ my band d 12 feat eminem] [http://joshuaw-wise.ifrance.com/img/styles/confessiones/ confessiones] [http://zeakk.ifrance.com/resources/articles/verona-madrid.htm verona madrid biglietti aerei] [http://cocopuff66.ifrance.com/text/directory/catrina-suite/ catrina suite] [http://horcrionebay.ifrance.com/resources/articles/li-pensiero.htm li pensiero di giuseppe ungaretti] [http://krychan.ifrance.com/content/view/elise-.htm elise 111 s] [http://gajar.ifrance.com/html/dela-candela.htm dela candela] [http://smegmacheez.ifrance.com/content/view/stacey-dash/ stacey dash farting] [http://trumanburb.ifrance.com/view/new/witec.htm witec] [http://mfirishka.ifrance.com/view/new/playground.htm playground] [http://zeakk.ifrance.com/resources/articles/canzoni-di.htm canzoni di ovindoli] [http://krychan.ifrance.com/content/view/sex-brazil.htm sex brazil] [http://smegmacheez.ifrance.com/content/view/ww-tf/ ww tf1 fr] [http://gajar.ifrance.com/html/convertitori-ogg.htm convertitori ogg mp3] [http://nokros.ifrance.com/data/dekster/ dekster] [http://atrayah.ifrance.com/topic/flash-erotici.htm flash erotici] [http://call-shotgun.ifrance.com/view/new/adsl-veloce/ adsl veloce] [http://nokros.ifrance.com/data/jetix-d/ jetix 3d soccer] [http://mfirishka.ifrance.com/view/new/treno-con.htm treno con parole] [http://lightmyfire0214.ifrance.com/topic/philips-/ philips 17 dvi] [http://lightmyfire0214.ifrance.com/topic/kafka/ kafka] [http://smegmacheez.ifrance.com/content/view/la-sportiva/ la sportiva nepal trek] [http://alishca-st.ifrance.com/text/directory/saponi-al.htm saponi al neem] [http://atrayah.ifrance.com/topic/federico-giulia.htm federico giulia] [http://sm4.ifrance.com/lib/obsecion-english/ obsecion english] [http://gabe95.ifrance.com/html/bacardi/ bacardi] [http://flawedamythyst.ifrance.com/img/styles/news-su.htm news su lee ryan dei blue] [http://call-shotgun.ifrance.com/view/new/carling/ carling] [http://joshuaw-wise.ifrance.com/img/styles/lavastoviglie-/ lavastoviglie 50 cm] [http://flawedamythyst.ifrance.com/img/styles/s-e.htm s e f] [http://joshuaw-wise.ifrance.com/img/styles/paris-hiltom/ paris hiltom] [http://mfirishka.ifrance.com/view/new/acer.htm acer 533] [http://gabe95.ifrance.com/html/hotel-mp/ hotel mp3] [http://smegmacheez.ifrance.com/content/view/montalbano-vol/ montalbano. vol. 01] [http://joshuaw-wise.ifrance.com/img/styles/fim-cisl/ fim cisl] [http://cocopuff66.ifrance.com/text/directory/divx-player/ divx player radio] [http://mfirishka.ifrance.com/view/new/scarpa-lotto.htm scarpa lotto] [http://zeakk.ifrance.com/resources/articles/dainese-crunch.htm dainese crunch] [http://nokros.ifrance.com/data/mina-platinum/ mina platinum collection] [http://zeakk.ifrance.com/resources/articles/qtek-stilo.htm qtek stilo] [http://zeakk.ifrance.com/resources/articles/succo-di.htm succo di mirtillo rosso] [http://gajar.ifrance.com/html/ultimo-canto.htm ultimo canto di saffo] [http://lightmyfire0214.ifrance.com/topic/cooperativa-sociale/ cooperativa sociale] [http://gabe95.ifrance.com/html/geronimo/ geronimo] [http://smegmacheez.ifrance.com/content/view/collo-dacciaio/ collo dacciaio] [http://zeakk.ifrance.com/resources/articles/ginnastica.htm ginnastica] [http://trumanburb.ifrance.com/view/new/la-notte.htm la notte del desiderio] [http://alishca-st.ifrance.com/text/directory/villaggio-vacanza.htm villaggio vacanza minorca] [http://squoi-oop.ifrance.com/topic/labo-europa/ labo europa srl padova] [http://zeakk.ifrance.com/resources/articles/gps-destinator.htm gps destinator] [http://dejablu503.ifrance.com/description/lib/tommy-e.htm tommy e carolina] [http://sm4.ifrance.com/lib/inps-como/ inps como] [http://gabe95.ifrance.com/html/lettore-mp/ lettore mp3 creative zen touch 40 gb] [http://alishca-st.ifrance.com/text/directory/ingrassare.htm ingrassare] [http://gabe95.ifrance.com/html/emuladore/ emuladore] [http://alishca-st.ifrance.com/text/directory/incontri-on.htm incontri on line] [http://joshuaw-wise.ifrance.com/img/styles/wells-dickie/ wells, dickie] [http://krychan.ifrance.com/content/view/boy-gay.htm boy gay] [http://zeakk.ifrance.com/resources/articles/profumi-donna.htm profumi donna krizia] [http://sm4.ifrance.com/lib/posizionamento-lycos/ posizionamento lycos] [http://atrayah.ifrance.com/topic/potatura-kiwi.htm potatura kiwi] [http://call-shotgun.ifrance.com/view/new/dito-a/ dito a martello] [http://flawedamythyst.ifrance.com/img/styles/cappe-da.htm cappe da cucina] [http://horcrionebay.ifrance.com/resources/articles/dif.htm dif] [http://flawedamythyst.ifrance.com/img/styles/foggiacalciomania.htm foggiacalciomania] [http://joshuaw-wise.ifrance.com/img/styles/allievo/ allievo] [http://alishca-st.ifrance.com/text/directory/v-nero.htm v3 nero italia] [http://sm4.ifrance.com/lib/miss-dior/ miss dior] [http://sm4.ifrance.com/lib/ignis-auto/ ignis auto nuova] [http://lightmyfire0214.ifrance.com/topic/binocolo-tascabile/ binocolo tascabile] [http://sm4.ifrance.com/lib/tom-tom/ tom tom spagna] [http://squoi-oop.ifrance.com/topic/rodaggio-matrimoniale/ rodaggio matrimoniale] [http://joshuaw-wise.ifrance.com/img/styles/suonerie-midi/ suonerie midi per nec e616v gratis] [http://gajar.ifrance.com/html/extreme-memory.htm extreme memory card] [http://gajar.ifrance.com/html/gazzettadellosport-it.htm gazzettadellosport it] [http://lightmyfire0214.ifrance.com/topic/nikon-as/ nikon as-15] [http://flawedamythyst.ifrance.com/img/styles/surveys.htm surveys] [http://alishca-st.ifrance.com/text/directory/katina-paxinou.htm katina paxinou] [http://smegmacheez.ifrance.com/content/view/gps-bluetooth/ gps bluetooth nokia 6600] [http://mfirishka.ifrance.com/view/new/michelangelo-adsl.htm michelangelo adsl wireless] [http://joshuaw-wise.ifrance.com/img/styles/daniele-gas/ daniele gas] [http://lightmyfire0214.ifrance.com/topic/gioco-avventura/ gioco avventura guerra] [http://zeakk.ifrance.com/resources/articles/jellyworld-com.htm jellyworld com] [http://flawedamythyst.ifrance.com/img/styles/goccia-su.htm goccia su goccia] [http://zeakk.ifrance.com/resources/articles/manuale-guida.htm manuale guida testo tecnico] [http://trumanburb.ifrance.com/view/new/fattoria.htm fattoria 2] [http://smegmacheez.ifrance.com/content/view/corrente-conto/ corrente conto virtuale] [http://joshuaw-wise.ifrance.com/img/styles/einstein/ einstein] [http://cocopuff66.ifrance.com/text/directory/golia-alla/ golia alla conquista di bagdad] [http://squoi-oop.ifrance.com/topic/hendel-joy/ hendel joy to the world] [http://sm4.ifrance.com/lib/counter-strike/ counter strike] [http://sm4.ifrance.com/lib/vvf/ vvf] [http://joshuaw-wise.ifrance.com/img/styles/monitor-lcd/ monitor lcd acer al1751as] [http://squoi-oop.ifrance.com/topic/one-shot/ one shot 90 volume 2] [http://call-shotgun.ifrance.com/view/new/albuquerque-ristorante/ albuquerque ristorante] [http://dejablu503.ifrance.com/description/lib/transexuals.htm transexuals] [http://joshuaw-wise.ifrance.com/img/styles/pieraccioni/ pieraccioni] [http://mfirishka.ifrance.com/view/new/albergo-nantes.htm albergo nantes] [http://cocopuff66.ifrance.com/text/directory/ministero-della/ ministero della salute ecm] [http://gajar.ifrance.com/html/lesbiche-senza.htm lesbiche senza dialer] [http://joshuaw-wise.ifrance.com/img/styles/thrustmaster-ferrari/ thrustmaster ferrari] [http://nokros.ifrance.com/data/sdram-mb/ sdram 1024mb] [http://krychan.ifrance.com/content/view/le-maschere.htm le maschere colombina] [http://horcrionebay.ifrance.com/resources/articles/auto-modellista.htm auto modellista] [http://smegmacheez.ifrance.com/content/view/wwo-vienio/ wwo vienio pele u ciebie w miescie] [http://squoi-oop.ifrance.com/topic/nissan-gpl/ nissan gpl] [http://mfirishka.ifrance.com/view/new/tamyra-gray.htm tamyra gray] [http://alishca-st.ifrance.com/text/directory/musica-per.htm musica per signora] [http://alishca-st.ifrance.com/text/directory/heiger.htm heiger] [http://lekusya.ifrance.com/library/html/aculaser-c/ aculaser c1100 epson stampanti] [http://joshuaw-wise.ifrance.com/img/styles/atlantis-router/ atlantis router ra3] [http://lekusya.ifrance.com/library/html/codes-hex/ codes hex tps] [http://trumanburb.ifrance.com/view/new/miserlou.htm miserlou] [http://alishca-st.ifrance.com/text/directory/hotel-economici.htm hotel economici barcellona] [http://squoi-oop.ifrance.com/topic/scherzi-da/ scherzi da fare ai matrimoni] [http://atrayah.ifrance.com/topic/sony-.htm sony - dcrdvd92] [http://gajar.ifrance.com/html/driver-motorola.htm driver motorola phone c350] [http://krychan.ifrance.com/content/view/le-carte.htm le carte di yu-gi-oh] [http://trumanburb.ifrance.com/view/new/incontri-sexi.htm incontri sexi] [http://zeakk.ifrance.com/resources/articles/equilize.htm equilize] [http://flawedamythyst.ifrance.com/img/styles/digitale-terrestre.htm digitale terrestre la7] [http://squoi-oop.ifrance.com/topic/kermer/ kermer] [http://alishca-st.ifrance.com/text/directory/im-alto.htm im alto mare] [http://horcrionebay.ifrance.com/resources/articles/stampante-laser.htm stampante laser canon lbp 2000] [http://cocopuff66.ifrance.com/text/directory/yugiyo/ yugiyo] [http://call-shotgun.ifrance.com/view/new/jvc-gr/ jvc gr d53] [http://horcrionebay.ifrance.com/resources/articles/je-noi.htm je noi pas compris] [http://smegmacheez.ifrance.com/content/view/tuttogratis-per/ tuttogratis per nokia] [http://smegmacheez.ifrance.com/content/view/www-spaccanapoli/ www spaccanapoli] [http://cocopuff66.ifrance.com/text/directory/donna-cerca/ donna cerca singolo] {{task}}
 
Perform the following three XPath queries on the XML Document below:
Line 87:
</cfsavecontent>
<cfset xml = xmlParse(xmlString)>
&lt;!--- First Task --->
<cfset itemSearch = xmlSearch(xml, "//item")>
&lt;!--- item = the first Item (xml element object) --->
<cfset item = itemSearch[1]>
&lt;!--- Second Task --->
<cfset priceSearch = xmlSearch(xml, "//price")>
&lt;!--- loop and print each price --->
<cfloop from="1" to="#arrayLen(priceSearch)#" index="i">
#priceSearch[i].xmlText#&lt;br/>
</cfloop>
&lt;!--- Third Task --->
&lt;!--- array of all the name elements --->
<cfset names = xmlSearch(xml, "//name")>
&lt;!--- visualize the results --->
<cfdump var="#variables#">
 
==[[JavaScript]]==
[[Category:JavaScript]]
 
'''Interpreter:''' Firefox 2.0
 
//create XMLDocument object from file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
xhr.send(null);
var doc = xhr.responseXML;
//get first <item> element
var firstItem = doc.evaluate( '//item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
alert( firstItem.textContent );
//output contents of <price> elements
var prices = doc.evaluate( '//price', doc, null, XPathResult.ANY_TYPE, null );
for( var price = prices.iterateNext(); price != null; price = prices.iterateNext() ) {
alert( price.textContent );
}
//add <name> elements to array
var names = doc.evaluate( '//name', doc, null, XPathResult.ANY_TYPE, null);
var namesArray = [];
for( var name = names.iterateNext(); name != null; name = names.iterateNext() ) {
namesArray.push( name );
}
alert( namesArray );
 
Although some browsers support XPath, working with XML is much easier with E4X.
 
//create XML object from file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
xhr.send(null);
var doc = new XML(xhr.responseText);
//get first <item> element
var firstItem = doc..item[0];
alert( firstItem );
//output contents of <price> elements
for each( var price in doc..price ) {
alert( price );
}
//add <name> elements to array
var names = [];
for each( var name in doc..name ) {
names.push( name );
}
alert( names );
 
==[[Perl]]==
[[Category:Perl]]
use XML::XPath qw();
my $x = XML::XPath->new('<inventory ... </inventory>');
[$x->findnodes('//item[1]')->get_nodelist]->[0];
print $x->findnodes_as_string('//price');
$x->findnodes('//name')->get_nodelist;
 
==[[PHP]]==
[[Category:PHP]]
<?php
//PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0)
$doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>');
//Load from file instead with $doc = DOMDocument::load('filename');
$xpath = new DOMXPath($doc);
/*
1st Task: Retrieve the first "item" element
*/
$nodelist = $xpath->query('//item');
$result = $nodelist->item(0);
/*
2nd task: Perform an action on each "price" element (print it out)
*/
$nodelist = $xpath->query('//price');
for($i = 0; $i < $nodelist->length; $i++)
{
//print each price element in the DOMNodeList instance, $nodelist, as text/xml followed by a newline
print $doc->saveXML($nodelist->item($i))."\n";
}
/*
3rd Task: Get an array of all the "name" elements
*/
$nodelist = $xpath->query('//name');
//our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList
$result = array();
//a different way of iterating through the DOMNodeList
foreach($nodelist as $node)
{
$result[] = $node;
}
 
==[[Ruby]]==
[[Category:Ruby]]
#Example taken from the REXML tutorial (http://www.germane-software.com/software/rexml/docs/tutorial.html)
require "rexml/document"
include REXML
#create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string)
doc = Document.new(
%q@<inventory title="OmniCorp Store #45x10^3">
...
</inventory>
@
)
# The invisibility cream is the first <item>
invisibility = XPath.first( doc, "//item" )
# Prints out all of the prices
XPath.each( doc, "//price") { |element| puts element.text }
# Gets an array of all of the "name" elements in the document.
names = XPath.match( doc, "//name" )

Revision as of 06:33, 24 August 2007

Task
XML/XPath
You are encouraged to solve this task according to the task description, using any language you may know.

Perform the following three XPath queries on the XML Document below:

  • Retrieve the first "item" element
  • Perform an action on each "price" element (print it out)
  • Get an array of all the "name" elements

XML Document:

<inventory title="OmniCorp Store #45x10^3">
  
<item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> <price>23.99</price> <description>Levitate yourself for up to 3 hours per application</description> </item>
<item upc="485672034" stock="653"> <name>Blork and Freen Instameal</name> <price>4.95</price> <description>A tasty meal in a tablet; just add water</description> </item> <item upc="132957764" stock="44"> <name>Grob winglets</name> <price>3.56</price> <description>Tender winglets of Grob. Just add water</description> </item>
</inventory>

C#

 XmlReader XReader;

 // Either read the xml from a string ...
 XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));

 // ... or read it from the file system.
 XReader = XmlReader.Create("xmlfile.xml");

 // Create a XPathDocument object (which implements the IXPathNavigable interface)
 // which is optimized for XPath operation. (very fast).
 IXPathNavigable XDocument = new XPathDocument(XReader);

 // Create a Navigator to navigate through the document.
 XPathNavigator Nav = XDocument.CreateNavigator();
 Nav = Nav.SelectSingleNode("//item");

 // Move to the first element of the selection. (if available).
 if(Nav.MoveToFirst())
 {
   Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.
 }

 // Get an iterator to loop over multiple selected nodes.
 XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");

 while (Iterator.MoveNext())
 {
   Console.WriteLine(Iterator.Current.Value);
 }

 Iterator = XDocument.CreateNavigator().Select("//name");

 // Use a generic list.
 List<string> NodesValues = new List<string>();

 while (Iterator.MoveNext())
 {
   NodesValues.Add(Iterator.Current.Value);
 }

 // Convert the generic list to an array and output the count of items.
 Console.WriteLine(NodesValues.ToArray().Length);

ColdFusion

 <cfsavecontent variable="xmlString">
 <inventory
 ...
 </inventory>
 </cfsavecontent>
 <cfset xml = xmlParse(xmlString)>
 <!--- First Task --->
 <cfset itemSearch = xmlSearch(xml, "//item")>
 <!--- item = the first Item (xml element object) --->
 <cfset item = itemSearch[1]>
 <!--- Second Task --->
 <cfset priceSearch = xmlSearch(xml, "//price")>
 <!--- loop and print each price --->
 <cfloop from="1" to="#arrayLen(priceSearch)#" index="i">
   #priceSearch[i].xmlText#<br/>
 </cfloop>
 <!--- Third Task --->
 <!--- array of all the name elements --->
 <cfset names = xmlSearch(xml, "//name")>
 <!--- visualize the results --->
 <cfdump var="#variables#">

JavaScript

Interpreter: Firefox 2.0

//create XMLDocument object from file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
xhr.send(null);
var doc = xhr.responseXML;

//get first <item> element
var firstItem = doc.evaluate( '//item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
alert( firstItem.textContent );

//output contents of <price> elements
var prices = doc.evaluate( '//price', doc, null, XPathResult.ANY_TYPE, null );
for( var price = prices.iterateNext(); price != null; price = prices.iterateNext() ) {
  alert( price.textContent );
}

//add <name> elements to array
var names = doc.evaluate( '//name', doc, null, XPathResult.ANY_TYPE, null);
var namesArray = [];
for( var name = names.iterateNext(); name != null; name = names.iterateNext() ) {
  namesArray.push( name );
}
alert( namesArray );

Although some browsers support XPath, working with XML is much easier with E4X.

//create XML object from file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
xhr.send(null);
var doc = new XML(xhr.responseText);

//get first <item> element
var firstItem = doc..item[0];
alert( firstItem );

//output contents of <price> elements
for each( var price in doc..price ) {
  alert( price );
}

//add <name> elements to array
var names = [];
for each( var name in doc..name ) {
  names.push( name );
}
alert( names );

Perl

use XML::XPath qw();
my $x = XML::XPath->new('<inventory ... </inventory>');

[$x->findnodes('//item[1]')->get_nodelist]->[0];
print $x->findnodes_as_string('//price');
$x->findnodes('//name')->get_nodelist;

PHP

 <?php
 //PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0)
 $doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>');
 //Load from file instead with $doc = DOMDocument::load('filename');
 $xpath = new DOMXPath($doc);
 /* 
     1st Task: Retrieve the first "item" element
 */
 $nodelist = $xpath->query('//item');
 $result = $nodelist->item(0);
 /* 
     2nd task: Perform an action on each "price" element (print it out)
 */
 $nodelist = $xpath->query('//price');
 for($i = 0; $i < $nodelist->length; $i++)
 {
   //print each price element in the DOMNodeList instance, $nodelist, as text/xml followed by a newline
   print $doc->saveXML($nodelist->item($i))."\n";
 }
 /* 
     3rd Task: Get an array of all the "name" elements
 */
 $nodelist = $xpath->query('//name');
 //our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList
 $result = array(); 
 //a different way of iterating through the DOMNodeList
 foreach($nodelist as $node)
 {
   $result[] = $node; 
 }

Ruby

 #Example taken from the REXML tutorial (http://www.germane-software.com/software/rexml/docs/tutorial.html)
 require "rexml/document"
 include REXML
 #create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string)
 doc = Document.new(
         %q@<inventory title="OmniCorp Store #45x10^3">
              ...
            </inventory>
           @
                           )
 # The invisibility cream is the first <item>
 invisibility = XPath.first( doc, "//item" ) 
 # Prints out all of the prices
 XPath.each( doc, "//price") { |element| puts element.text }
 # Gets an array of all of the "name" elements in the document.
 names = XPath.match( doc, "//name" )