XML/XPath: Difference between revisions

From Rosetta Code
< XML
Content added Content deleted
mNo edit summary
No edit summary
Line 1: Line 1:
{{task}}
[http://uve.rigour.info/blog/nino-rota.htm nino rota la strada] [http://speed.rigour.info/skye-sweetnam.htm skye sweetnam] [http://here.rigour.info/blog/agriturismo-siviglia.htm agriturismo siviglia] [http://here.rigour.info/blog/orologi-casio.htm orologi casio data bank] [http://milano.rigour.info/sony-cybershot.htm sony cybershot w7] [http://pagina.rigour.info/risultati-motomondiale/ risultati motomondiale 2004] [http://uve.rigour.info/blog/un-paradiso.htm un paradiso senza biliardo] [http://milano.rigour.info/eleni.htm eleni] [http://guest.rigour.info/library/html/pca/ pca] [http://online.rigour.info/batterie-per/ batterie per cellulari ericsson t39] [http://dir.rigour.info/fotocopiatrice-scanner/ fotocopiatrice scanner stampante a3] [http://note.rigour.info/content/view/gabriel-amano.htm gabriel amano] [http://web.rigour.info/gioca-jouer/ gioca jouer midi] [http://all.rigour.info/for-men/ for men rivista] [http://here.rigour.info/blog/giochi-con.htm giochi con gay e lesbiche] [http://guest.rigour.info/library/html/copertina-cd/ copertina cd freeware] [http://italy.rigour.info/blog/urke.htm urke] [http://all.rigour.info/videogioco-on/ videogioco on line] [http://web.rigour.info/dj-console/ dj console] [http://down.rigour.info/blog/pixar.htm pixar] [http://note.rigour.info/content/view/good-charlotte.htm good charlotte dvd] [http://speed.rigour.info/sony-walkman.htm sony walkman mp3] [http://online.rigour.info/hpcompaqipaq/ hp-compaq-ipaq 6345] [http://content.rigour.info/html/quam-mirabilis/ quam mirabilis] [http://web.rigour.info/www-playstation/ www playstation it] [http://online.rigour.info/diga-di/ diga di assuan] [http://web.rigour.info/cavalcata-selvaggia/ cavalcata selvaggia] [http://online.rigour.info/donne-nere/ donne nere penetrazioni anali] [http://paga.rigour.info/oakley-twenty/ oakley twenty] [http://pagina.rigour.info/fasciatoio-vasca/ fasciatoio vasca] [http://load.rigour.info/view/new/se-ci.htm se ci credi anche tu] [http://guest.rigour.info/library/html/karaoke-file/ karaoke file midi] [http://paga.rigour.info/jaguar/ jaguar 3 2] [http://italy.rigour.info/blog/i-pugni.htm i pugni in tasca] [http://load.rigour.info/view/new/office-licenza.htm office licenza] [http://note.rigour.info/content/view/edge-cellulari.htm edge cellulari bluetooth] [http://milano.rigour.info/appunti-diritto.htm appunti diritto tributario] [http://load.rigour.info/view/new/blue-video.htm blue video] [http://note.rigour.info/content/view/mutazioni-generali.htm mutazioni generali] [http://note.rigour.info/content/view/cd-.htm cd - rw 8 cm] [http://dir.rigour.info/floppy-esterno/ floppy esterno usb] [http://online.rigour.info/canon-ef/ canon ef fisheye] [http://online.rigour.info/camasutra-foto/ camasutra foto] [http://guest.rigour.info/library/html/dragostea-din/ dragostea din tei dj ross] [http://paga.rigour.info/garlando/ garlando 200] [http://all.rigour.info/verona-calcio/ verona calcio] [http://milano.rigour.info/prestito-otranto.htm prestito otranto] [http://note.rigour.info/content/view/lettore-jpg.htm lettore jpg] [http://online.rigour.info/moder-times/ moder times j five] [http://gratis.rigour.info/content/view/fotocamera-cybershot.htm fotocamera cybershot sony t7] [http://paga.rigour.info/croazia-hotel/ croazia hotel] [http://dir.rigour.info/paradiso-beach/ paradiso beach] [http://pagina.rigour.info/ancora-vita/ ancora vita] [http://blog.rigour.info/web/mundo-porno/ mundo porno] [http://blog.rigour.info/web/festivalbar-blue/ festivalbar blue 2004] [http://uve.rigour.info/blog/pioneer-vsxcs.htm pioneer vsx-c402-s] [http://load.rigour.info/view/new/quel-giorno.htm quel giorno a rio] [http://blog.rigour.info/web/gli-orsi/ gli orsi vanno in giappone] [http://up.rigour.info/description/lib/wisin-y.htm wisin y yandel live] [http://pagina.rigour.info/logitech-quickcam/ logitech quickcam communicate] [http://dir.rigour.info/data-prova/ data prova esami gru iv serie speciale] [http://blog.rigour.info/web/fax/ fax 530] [http://pagina.rigour.info/bottone/ bottone] [http://blog.rigour.info/web/enricke/ enricke] [http://online.rigour.info/arbaud-joseph/ arbaud, joseph d-] [http://down.rigour.info/blog/staffa-accessori.htm staffa accessori samsung audio video] [http://speed.rigour.info/volvo-v.htm volvo v50 2 0 d summum] [http://content.rigour.info/html/sophia-loren/ sophia loren] [http://load.rigour.info/view/new/videocamera-canon.htm videocamera canon mv -790] [http://italy.rigour.info/blog/try-tradotta.htm try tradotta] [http://paga.rigour.info/buczkowski-leopold/ buczkowski, leopold] [http://up.rigour.info/description/lib/cubo-magico.htm cubo magico] [http://up.rigour.info/description/lib/juegos-de.htm juegos de mario bros] [http://web.rigour.info/asus-av/ asus a8v e deluxe via k8t890] [http://uve.rigour.info/blog/download-yetisports.htm download yetisports 7] [http://gratis.rigour.info/content/view/montoni.htm montoni] [http://here.rigour.info/blog/optio-pentax.htm optio pentax] [http://speed.rigour.info/la-macchina.htm la macchina dei gelati] [http://speed.rigour.info/sony-cuffie.htm sony cuffie 5 1] [http://pagina.rigour.info/lettore-mp/ lettore mp3 radio 1g] [http://it.rigour.info/topic/apera/ apera] [http://blog.rigour.info/web/negozi-vendita/ negozi vendita mobili afgani] [http://milano.rigour.info/testi-di.htm testi di canzoni it] [http://gratis.rigour.info/content/view/idropulitrice-professionale.htm idropulitrice professionale 150] [http://online.rigour.info/www-laura/ www laura engel it] [http://uve.rigour.info/blog/strumenti-chirurgici.htm strumenti chirurgici ivg] [http://content.rigour.info/html/polar-t/ polar t-31] [http://milano.rigour.info/miazzina.htm miazzina] [http://gratis.rigour.info/content/view/palmare-fujitsu.htm palmare fujitsu siemens] [http://web.rigour.info/behead-kim/ behead kim sun] [http://paga.rigour.info/andrews-virginia/ andrews virginia libri] [http://paga.rigour.info/travan-tr/ travan tr5] [http://online.rigour.info/pornio-video/ pornio video] [http://down.rigour.info/blog/omnia.htm omnia] [http://content.rigour.info/html/vacanza-affitto/ vacanza affitto como] [http://pagina.rigour.info/inside-jupiter/ inside jupiter] [http://note.rigour.info/content/view/dragostea-den.htm dragostea den tea] [http://it.rigour.info/topic/haiduci-gabry/ haiduci gabry ponte] [http://pagina.rigour.info/el-mundo/ el mundo de rastafari] [http://all.rigour.info/raz-dwa/ raz dwa trzy] [http://note.rigour.info/content/view/jassica-biel.htm jassica biel] [http://speed.rigour.info/charlotte-gallery.htm charlotte gallery] [http://pagina.rigour.info/f-leali/ f leali] [http://up.rigour.info/description/lib/logorrea.htm logorrea] [http://here.rigour.info/blog/traduttore-spagnolo.htm traduttore spagnolo] [http://italy.rigour.info/blog/microsoft-office.htm microsoft office per xp] [http://milano.rigour.info/batajsk.htm batajsk] [http://web.rigour.info/peg-perego/ peg perego modular system pliko] [http://web.rigour.info/erotc/ erotc] [http://online.rigour.info/pocket-kingdom/ pocket kingdom] [http://content.rigour.info/html/jvc-ths/ jvc th-s1] [http://it.rigour.info/topic/sanyo-home/ sanyo home theatre] [http://dir.rigour.info/de-noche/ de noche en la ciudad] [http://load.rigour.info/view/new/piron-armand.htm piron, armand j.] [http://here.rigour.info/blog/ruocco.htm ruocco] [http://milano.rigour.info/eric-prytz.htm eric prytz call on me] [http://online.rigour.info/umberto-poli/ umberto poli] [http://it.rigour.info/topic/minghi-mietta/ minghi mietta] [http://blog.rigour.info/web/software-dj/ software dj] [http://paga.rigour.info/black-pearl/ black pearl jam] [http://up.rigour.info/description/lib/la-vergine.htm la vergine sotto il tetto] [http://blog.rigour.info/web/nicholas-e/ nicholas e berg] [http://milano.rigour.info/nidi-darac.htm nidi darac] [http://web.rigour.info/antivirus-panda/ antivirus panda titanium 2006] [http://paga.rigour.info/kyosho-caliber/ kyosho caliber] [http://online.rigour.info/hard-disk/ hard disk mini] [http://web.rigour.info/freakys/ freakys] [http://paga.rigour.info/helico/ helico] [http://paga.rigour.info/sharik/ sharik] [http://milano.rigour.info/sting-feat.htm sting feat cray david] [http://here.rigour.info/blog/nicoletti.htm nicoletti] [http://gratis.rigour.info/content/view/serie-.htm serie 7 bmw] [http://all.rigour.info/ups-e/ ups e pdu] [http://web.rigour.info/www-tigre/ www tigre it] [http://up.rigour.info/description/lib/grottammare.htm grottammare] [http://content.rigour.info/html/www-nellyville/ www nellyville com] [http://note.rigour.info/content/view/resultados-de.htm resultados de comipems] [http://guest.rigour.info/library/html/hp/ hp 1150] [http://load.rigour.info/view/new/valentino-azzurro.htm valentino azzurro] [http://web.rigour.info/fujifilm-finepix/ fujifilm finepix f610] [http://dir.rigour.info/decrypter/ decrypter] [http://guest.rigour.info/library/html/sammichele-ba/ sammichele ba] [http://milano.rigour.info/kamsutra.htm kamsutra] [http://content.rigour.info/html/toe-rings/ toe rings] [http://italy.rigour.info/blog/e-la.htm e la notte se ne va] [http://blog.rigour.info/web/nova-art/ nova art explosion] [http://web.rigour.info/goldsmith-oliver/ goldsmith, oliver] [http://load.rigour.info/view/new/programmi-per.htm programmi per funcard] [http://paga.rigour.info/answer/ answer] [http://up.rigour.info/description/lib/epson-n.htm epson n1200] [http://it.rigour.info/topic/il-pianeta/ il pianeta vivente i mari d erba] [http://blog.rigour.info/web/pereyra/ pereyra] [http://content.rigour.info/html/sony-vgn/ sony vgn s4hp] [http://speed.rigour.info/volvo.htm volvo 2 3] [http://pagina.rigour.info/divani-letto/ divani letto] [http://milano.rigour.info/ted-bundy.htm ted bundy] [http://it.rigour.info/topic/hp-cae/ hp c4844ae] [http://here.rigour.info/blog/pettenati.htm pettenati] [http://down.rigour.info/blog/case-per.htm case per hard disk esterno] [http://up.rigour.info/description/lib/les-deux.htm les deux alpes] [http://note.rigour.info/content/view/video-boulevard.htm video boulevard of broken dreams] [http://guest.rigour.info/library/html/ww-virginio/ ww virginio it] [http://pagina.rigour.info/poster-vendita/ poster vendita] [http://milano.rigour.info/stampante-multifunzione.htm stampante multifunzione copiatrice] [http://web.rigour.info/pagine-bianche/ pagine bianche avellino] [http://blog.rigour.info/web/consulenza-internet/ consulenza internet marketing] [http://online.rigour.info/tommi-v/ tommi v la serenissima] [http://all.rigour.info/normas-del/ normas del imss para proyecto arq] [http://all.rigour.info/moderntalking/ moderntalking] [http://it.rigour.info/topic/ospedale-vicenza/ ospedale vicenza] [http://milano.rigour.info/dmc-panasonic.htm dmc panasonic] [http://here.rigour.info/blog/scarpe-da.htm scarpe da mare e barca] [http://content.rigour.info/html/dat-/ dat 40 external tape drive hp] [http://blog.rigour.info/web/immagini-rottweiller/ immagini rottweiller] [http://guest.rigour.info/library/html/flinta/ flinta] [http://blog.rigour.info/web/delta-fox/ delta fox] [http://online.rigour.info/la-cumbia/ la cumbia de los trapos] [http://here.rigour.info/blog/nude-fight.htm nude fight] [http://note.rigour.info/content/view/porno-alte.htm porno alte prestazioni] [http://here.rigour.info/blog/oktoberfest-.htm oktoberfest 2004 monaco] [http://dir.rigour.info/gioia-e/ gioia e rivoluzione] [http://pagina.rigour.info/pane-e/ pane e sale] [http://down.rigour.info/blog/looney-tunes.htm looney tunes - back in action] [http://down.rigour.info/blog/nvidia-geforce.htm nvidia geforce 6600 256mb] [http://online.rigour.info/istituto-salvemini/ istituto salvemini] [http://italy.rigour.info/blog/sicurezza-baby.htm sicurezza baby porte] [http://milano.rigour.info/dexther.htm dexther] [http://note.rigour.info/content/view/sloth.htm sloth] [http://paga.rigour.info/spartito-di/ spartito di adesso tu] [http://here.rigour.info/blog/gabriella-labate.htm gabriella labate] [http://it.rigour.info/topic/rivendite-animali/ rivendite animali provincia di arezzo] [http://up.rigour.info/description/lib/digital-camera.htm digital camera sony dsc] [http://speed.rigour.info/registratore-mini.htm registratore mini disc portatile] [http://pagina.rigour.info/fotografie-erotiche/ fotografie erotiche] [http://here.rigour.info/blog/mellin-latte.htm mellin latte in polvere] [http://paga.rigour.info/dafa/ dafa] [http://web.rigour.info/vicario-comunication/ vicario comunication] [http://up.rigour.info/description/lib/orologio-citizen.htm orologio citizen] [http://dir.rigour.info/google-nel/ google nel web] [http://guest.rigour.info/library/html/locandine/ locandine] {{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 00:02, 22 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" )