XML/XPath: Difference between revisions

From Rosetta Code
< XML
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://highbulp.ifrance.com/images/small/tutti-videocamere/ tutti videocamere] [http://girlwho-is.ifrance.com/img/styles/un-ora.htm un ora sola ti vorrei giorgia] [http://lovereceier.ifrance.com/lib/photo-shop.htm photo shop] [http://tat-ooin.ifrance.com/resources/articles/milano-costa.htm milano costa rica] [http://lordsander.ifrance.com/topic/televisore-lcd.htm televisore lcd 27] [http://voltia.ifrance.com/content/view/scavi.htm scavi] [http://highbulp.ifrance.com/images/small/cosa-sono/ cosa sono le nuvole] [http://oiyaoi.ifrance.com/images/small/accessori-culle/ accessori culle] [http://igaros.ifrance.com/lib/punto-van/ punto van 1 9 d] [http://tizolaa.ifrance.com/web/sesso-la/ sesso la prima volta] [http://girlwho-is.ifrance.com/img/styles/yves-saint.htm yves saint laurent] [http://tat-ooin.ifrance.com/resources/articles/breath-easy.htm breath easy mp3] [http://demurediablo.ifrance.com/library/html/foto-selen/ foto selen nuda] [http://lovereceier.ifrance.com/lib/siria.htm siria] [http://oiyaoi.ifrance.com/images/small/siae/ siae] [http://highbulp.ifrance.com/images/small/chema/ chema] [http://voltia.ifrance.com/content/view/teresa-raquin.htm teresa raquin] [http://jdawsona.ifrance.com/data/viedo-porno/ viedo porno] [http://oiyaoi.ifrance.com/images/small/googlr-com/ googlr com] [http://oiyaoi.ifrance.com/images/small/mah-jong/ mah jong solitario] [http://yeeden.ifrance.com/img/styles/gesu-lava/ gesu lava piu bianco] [http://jdawsona.ifrance.com/data/le-avventure/ le avventure di charlie] [http://speedofsoun.ifrance.com/text/directory/this-love.htm this love tradotto] [http://noxuhax.ifrance.com/content/view/orion-network.htm orion network communication srl] [http://girlwho-is.ifrance.com/img/styles/renault-modus.htm renault modus km zero] [http://tizolaa.ifrance.com/web/rayban/ ray-ban 3184] [http://lovereceier.ifrance.com/lib/decoder-digitali.htm decoder digitali e terrestri] [http://girlwho-is.ifrance.com/img/styles/galluppi.htm galluppi] [http://noxuhax.ifrance.com/content/view/grigne.htm grigne] [http://jdawsona.ifrance.com/data/nikon-/ nikon 80 200 d] [http://toofarfrommaybe.ifrance.com/view/new/film-rosso/ film rosso tre colori] [http://jdawsona.ifrance.com/data/video-red/ video red hot chili peppers] [http://jdawsona.ifrance.com/data/famiglio/ famiglio] [http://tat-ooin.ifrance.com/resources/articles/celebrity-porn.htm celebrity porn] [http://deviantrus.ifrance.com/topic/villaggio-puglia/ villaggio puglia] [http://kalian42.ifrance.com/text/directory/casus-belli/ casus belli] [http://deviantrus.ifrance.com/topic/fujitsu-siemens/ fujitsu siemens amilo a7640] [http://tizolaa.ifrance.com/web/house-party/ house party 1990] [http://tat-ooin.ifrance.com/resources/articles/www-live.htm www live score com] [http://kalian42.ifrance.com/text/directory/usb-pen/ usb pen drive 2 gb] [http://tizolaa.ifrance.com/web/lcd/ lcd 20 1600 1200] [http://oiyaoi.ifrance.com/images/small/fermasoldi-argento/ fermasoldi argento] [http://demurediablo.ifrance.com/library/html/tipos-de/ tipos de scanner] [http://oiyaoi.ifrance.com/images/small/nuttea/ nuttea] [http://tat-ooin.ifrance.com/resources/articles/voli-san.htm voli san francisco] [http://broadwaylili.ifrance.com/content/view/pornosnob.htm pornosnob] [http://akmokanzen.ifrance.com/images/small/panasonic-plasma.htm panasonic plasma tv] [http://oiyaoi.ifrance.com/images/small/offerte-lavoro/ offerte lavoro stlisti a lecce] [http://deviantrus.ifrance.com/topic/sbloccare-videofonini/ sbloccare videofonini tre] [http://highbulp.ifrance.com/images/small/chelsea-charm/ chelsea charm] [http://singaporepets.ifrance.com/library/html/palmare-navigatore.htm palmare navigatore ipaq] [http://singaporepets.ifrance.com/library/html/sms-gratis.htm sms gratis free] [http://yeeden.ifrance.com/img/styles/processore-intel/ processore intel 478] [http://voltia.ifrance.com/content/view/hurgada-hilton.htm hurgada hilton] [http://highbulp.ifrance.com/images/small/servant-orchestra/ servant orchestra video] [http://demurediablo.ifrance.com/library/html/volume-muscolare/ volume muscolare integratori] [http://voltia.ifrance.com/content/view/wallpaper-harry.htm wallpaper harry potter 10] [http://voltia.ifrance.com/content/view/roxette-ballad.htm roxette. ballad - p hits. the complete video collection] [http://yeeden.ifrance.com/img/styles/limosano/ limosano] [http://deviantrus.ifrance.com/topic/possibili-tracce/ possibili tracce] [http://toofarfrommaybe.ifrance.com/view/new/caratteri-ereditari/ caratteri ereditari] [http://yeeden.ifrance.com/img/styles/bad-boys/ bad boys ii] [http://highbulp.ifrance.com/images/small/movin-crusin/ movin crusin] [http://voltia.ifrance.com/content/view/candeejay.htm candeejay] [http://singaporepets.ifrance.com/library/html/web-cam.htm web cam gratis] [http://yeeden.ifrance.com/img/styles/mansioni-area/ mansioni area sicurezza aziendale] [http://yeeden.ifrance.com/img/styles/ofx/ ofx 560] [http://deviantrus.ifrance.com/topic/hyundai-hqpsr/ hyundai hqp421sr] [http://noxuhax.ifrance.com/content/view/ticket-one.htm ticket one] [http://toofarfrommaybe.ifrance.com/view/new/sex-pictures/ sex pictures] [http://deviantrus.ifrance.com/topic/alfa-romeo/ alfa romeo 156 1.6] [http://voltia.ifrance.com/content/view/tv-philips.htm tv philips 42 pollici al plasma] [http://girlwho-is.ifrance.com/img/styles/hp-psc.htm hp psc-1315] [http://lordsander.ifrance.com/topic/concorso-danza.htm concorso danza eugenio polyakov] [http://kalian42.ifrance.com/text/directory/camara-a/ camara a gas] [http://akmokanzen.ifrance.com/images/small/italia-it.htm italia1 it] [http://oiyaoi.ifrance.com/images/small/ophelie-winter/ ophelie winter] [http://tizolaa.ifrance.com/web/nordica-dobermann/ nordica dobermann] [http://akmokanzen.ifrance.com/images/small/philips-lcd.htm philips lcd tv] [http://yeeden.ifrance.com/img/styles/ljubav/ ljubav] [http://speedofsoun.ifrance.com/text/directory/marsh.htm marsh] [http://kalian42.ifrance.com/text/directory/scheda-madre/ scheda madre amd fsb 800 mhz] [http://akmokanzen.ifrance.com/images/small/gba-sp.htm gba sp accessori console] [http://tizolaa.ifrance.com/web/wwwagenziaentrate-it/ wwwagenziaentrate it] [http://yeeden.ifrance.com/img/styles/www-load/ www load a game it] [http://girlwho-is.ifrance.com/img/styles/miguel-enriquez.htm miguel enriquez maria morena] [http://akmokanzen.ifrance.com/images/small/streptococco.htm streptococco] [http://deviantrus.ifrance.com/topic/ufficio-forte/ ufficio forte dei marmo] [http://toofarfrommaybe.ifrance.com/view/new/ante-legno/ ante legno] [http://lordsander.ifrance.com/topic/piante-sempreverdi.htm piante sempreverdi] [http://girlwho-is.ifrance.com/img/styles/sea-monkeys.htm sea monkeys] [http://speedofsoun.ifrance.com/text/directory/maglie-ai.htm maglie ai ferri] [http://voltia.ifrance.com/content/view/cavo-s.htm cavo s video 10 mt] [http://singaporepets.ifrance.com/library/html/elenco-abbonati.htm elenco abbonati telecom internazionali] [http://igaros.ifrance.com/lib/indesit-wisl/ indesit wisl86] [http://tat-ooin.ifrance.com/resources/articles/inthe-shadows.htm inthe shadows] [http://voltia.ifrance.com/content/view/alta-stagione.htm alta stagione] [http://akmokanzen.ifrance.com/images/small/ultrabeat.htm ultrabeat] [http://broadwaylili.ifrance.com/content/view/durata-documento.htm durata documento di trasporto] [http://highbulp.ifrance.com/images/small/assicurazione-portogruaro/ assicurazione portogruaro] [http://tizolaa.ifrance.com/web/ati-radeon/ ati radeon 9800 pro all in wonder] [http://akmokanzen.ifrance.com/images/small/san-vito.htm san vito dei normanni] [http://lordsander.ifrance.com/topic/batterie-nokia.htm batterie nokia 6600] [http://jdawsona.ifrance.com/data/juventus-film/ juventus film dvd] [http://broadwaylili.ifrance.com/content/view/cruscotto-audi.htm cruscotto audi a3] [http://demurediablo.ifrance.com/library/html/matur/ matur] [http://speedofsoun.ifrance.com/text/directory/hana-melonova.htm hana melonova] [http://kalian42.ifrance.com/text/directory/sosia/ sosia] [http://highbulp.ifrance.com/images/small/drgon/ drgon] [http://akmokanzen.ifrance.com/images/small/one-more.htm one more night] [http://demurediablo.ifrance.com/library/html/wireless-compaq/ wireless compaq] [http://broadwaylili.ifrance.com/content/view/panorama-calendari.htm panorama calendari] [http://oiyaoi.ifrance.com/images/small/linkin-park/ linkin park numb] [http://jdawsona.ifrance.com/data/kiss-dvd/ kiss dvd 558] [http://highbulp.ifrance.com/images/small/hainan/ hainan] [http://speedofsoun.ifrance.com/text/directory/piosenka.htm piosenka] [http://noxuhax.ifrance.com/content/view/renato-zero.htm renato zero l equilibrista] [http://lordsander.ifrance.com/topic/progetto-.htm progetto diffusori dimensioni legno] [http://deviantrus.ifrance.com/topic/touareg-tdi/ touareg tdi r5] [http://lovereceier.ifrance.com/lib/comi-umberta.htm comi umberta bergamo] [http://akmokanzen.ifrance.com/images/small/pagine-bianche.htm pagine bianche padova] [http://yeeden.ifrance.com/img/styles/tv-sat/ tv sat usb] [http://lordsander.ifrance.com/topic/nitchevo.htm nitchevo] [http://jdawsona.ifrance.com/data/ucacaksin/ ucacaksin] [http://voltia.ifrance.com/content/view/midi-nuovi.htm midi nuovi] [http://tat-ooin.ifrance.com/resources/articles/cavasin.htm cavasin] [http://igaros.ifrance.com/lib/agriturismo-casalecchio/ agriturismo casalecchio di reno] [http://oiyaoi.ifrance.com/images/small/hotel-nevea/ hotel nevea] [http://tizolaa.ifrance.com/web/router-access/ router access point modem] [http://oiyaoi.ifrance.com/images/small/hector-lavoe/ hector lavoe] [http://noxuhax.ifrance.com/content/view/professione-giocattolo.htm professione... giocattolo] [http://oiyaoi.ifrance.com/images/small/ferraris-ferruccio/ ferraris ferruccio figli srl] [http://highbulp.ifrance.com/images/small/g-magazine/ g magazine] [http://voltia.ifrance.com/content/view/dibujo-en.htm dibujo en porno] [http://noxuhax.ifrance.com/content/view/www-sci.htm www sci] [http://demurediablo.ifrance.com/library/html/championship-manager/ championship manager 03 04 tips tricks t] [http://akmokanzen.ifrance.com/images/small/street-parade.htm street parade] [http://demurediablo.ifrance.com/library/html/istituto-oncologico/ istituto oncologico europeo milano] [http://deviantrus.ifrance.com/topic/scarica-she/ scarica she will be loved] [http://igaros.ifrance.com/lib/massala/ massala] [http://jdawsona.ifrance.com/data/toner-aculaser/ toner aculaser c1900] [http://igaros.ifrance.com/lib/poker-di/ poker di sangue] [http://highbulp.ifrance.com/images/small/processori-intel/ processori intel xeon 2 8 ghz 2 8] [http://oiyaoi.ifrance.com/images/small/driver-pentax/ driver pentax] [http://voltia.ifrance.com/content/view/bluetooth-handsfree.htm bluetooth handsfree] [http://speedofsoun.ifrance.com/text/directory/decapitato-usa.htm decapitato usa] [http://highbulp.ifrance.com/images/small/hotel-maxivillage/ hotel maxivillage sinai garden sharm] [http://oiyaoi.ifrance.com/images/small/www-cr/ www cr decorazioni com] [http://lordsander.ifrance.com/topic/batteria-per.htm batteria per videocamera panasonic] [http://noxuhax.ifrance.com/content/view/jolly-hotel.htm jolly hotel roma] [http://tat-ooin.ifrance.com/resources/articles/cartier-must.htm cartier must] [http://girlwho-is.ifrance.com/img/styles/bobbit.htm bobbit] [http://girlwho-is.ifrance.com/img/styles/colorare.htm colorare] [http://lordsander.ifrance.com/topic/satkeys.htm satkeys] [http://singaporepets.ifrance.com/library/html/officinale.htm officinale] [http://noxuhax.ifrance.com/content/view/chiles-com.htm chiles com mx] [http://lordsander.ifrance.com/topic/codice-d.htm codice d istallazione di the sims2] [http://jdawsona.ifrance.com/data/tv-lcd/ tv lcd 22] [http://yeeden.ifrance.com/img/styles/stefano-benni/ stefano benni] [http://lordsander.ifrance.com/topic/fano-contatto.htm fano contatto] [http://oiyaoi.ifrance.com/images/small/fujiko/ fujiko] [http://demurediablo.ifrance.com/library/html/proton-metal/ proton metal mr12] [http://oiyaoi.ifrance.com/images/small/router-/ router 4 porte] [http://yeeden.ifrance.com/img/styles/notebook-thoshiba/ notebook thoshiba] [http://speedofsoun.ifrance.com/text/directory/ericsson-hbh.htm ericsson hbh 602] [http://girlwho-is.ifrance.com/img/styles/marani.htm marani] [http://highbulp.ifrance.com/images/small/friends-anno/ friends anno 4 episodi 24] [http://singaporepets.ifrance.com/library/html/la-famiglia.htm la famiglia per freud] [http://lovereceier.ifrance.com/lib/kitty.htm kitty] [http://singaporepets.ifrance.com/library/html/roberto-cecchini.htm roberto cecchini] [http://oiyaoi.ifrance.com/images/small/mia-martini/ mia martini bolero] [http://igaros.ifrance.com/lib/web-tv/ web tv] [http://noxuhax.ifrance.com/content/view/bandiere-araldiche.htm bandiere araldiche] [http://oiyaoi.ifrance.com/images/small/albergo-alassio/ albergo alassio] [http://akmokanzen.ifrance.com/images/small/sony-dsc.htm sony dsc p93a] [http://demurediablo.ifrance.com/library/html/video-lettore/ video lettore dvd divx portatile con tv] [http://tizolaa.ifrance.com/web/casino-tressure/ casino tressure] [http://tat-ooin.ifrance.com/resources/articles/herceptin-iv.htm herceptin iv 1 fl 150 mg] [http://deviantrus.ifrance.com/topic/vita-di/ vita di ghandi] [http://singaporepets.ifrance.com/library/html/navigazione-satellitare.htm navigazione satellitare] [http://tat-ooin.ifrance.com/resources/articles/lavori-sessuali.htm lavori sessuali] [http://highbulp.ifrance.com/images/small/tripla-corona/ tripla corona] [http://kalian42.ifrance.com/text/directory/mp-innovix/ mp3 innovix] [http://broadwaylili.ifrance.com/content/view/preteen.htm preteen] [http://toofarfrommaybe.ifrance.com/view/new/denis-verdini/ denis verdini] [http://speedofsoun.ifrance.com/text/directory/esposizioni-lugano.htm esposizioni lugano] [http://voltia.ifrance.com/content/view/affitto-ufficio.htm affitto ufficio aquila] [http://deviantrus.ifrance.com/topic/correggio/ correggio] [http://voltia.ifrance.com/content/view/toshiba-satellite.htm toshiba satellite m40x 122] [http://tat-ooin.ifrance.com/resources/articles/latino.htm latino 9] [http://broadwaylili.ifrance.com/content/view/agroalimentare.htm agroalimentare] [http://girlwho-is.ifrance.com/img/styles/jvc-thar.htm jvc th-a75r] [http://kalian42.ifrance.com/text/directory/burn-this/ burn this house] [http://broadwaylili.ifrance.com/content/view/hyry-antti.htm hyry, antti] [http://lovereceier.ifrance.com/lib/assicurazione-mantova.htm assicurazione mantova] [http://tizolaa.ifrance.com/web/altalene-chicco/ altalene chicco] [http://kalian42.ifrance.com/text/directory/linfodrenaggio-vodder/ linfodrenaggio vodder] [http://toofarfrommaybe.ifrance.com/view/new/prezzi-della/ prezzi della fiat 1500] [http://deviantrus.ifrance.com/topic/costantino-vitaliano/ costantino vitaliano la scelta] [http://tat-ooin.ifrance.com/resources/articles/la-vera.htm la vera storia di eva peron] {{task}}


Perform the following three XPath queries on the XML Document below:
Perform the following three XPath queries on the XML Document below:
Line 87: Line 87:
</cfsavecontent>
</cfsavecontent>
<cfset xml = xmlParse(xmlString)>
<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 22:04, 19 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" )