XML/XPath: Difference between revisions
< XML
Content added Content deleted
mNo edit summary |
(revert spam) |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://end14april.ifrance.com/blog/free-xxx.html free xxx videoclip] [http://cincydj.ifrance.com/images/small/ragazze-con/ ragazze con voglia] [http://end14april.ifrance.com/blog/moduli-gratis.html moduli gratis] [http://furrysoap.ifrance.com/bulwerlytton-edward/ bulwer-lytton, edward george] [http://spirit-psyki.ifrance.com/lib/sexi-infermiere.html sexi infermiere] [http://competitio.ifrance.com/video-cicciolina/ video cicciolina gratis] [http://competitio.ifrance.com/orge-di/ orge di seso] [http://cincydj.ifrance.com/images/small/download-gratis/ download gratis gioco corse moto] [http://jnk713.ifrance.com/img/styles/ragazze-in/ ragazze in perizzoma] [http://competitio.ifrance.com/porno-gratisa/ porno gratisa] [http://elixirium.ifrance.com/lib/lecciso-nuda.html lecciso nuda] [http://tulip123456.ifrance.com/topic/shemale-sex.html shemale sex] [http://adrienneee.ifrance.com/blog/nauty-girl/ nauty girl] [http://elixirium.ifrance.com/lib/lecciso-loredana.html lecciso loredana nuda] [http://competitio.ifrance.com/bellissime-ragazze/ bellissime ragazze] [http://spirit-psyki.ifrance.com/lib/elin-foto.html elin foto nuda] [http://adrienneee.ifrance.com/blog/severina-nuda/ severina nuda] [http://cincydj.ifrance.com/images/small/foto-di/ foto di scambisti gratis] [http://adrienneee.ifrance.com/blog/videos-de/ videos de perreo gratis para bajar] [http://mi-kkiechang.ifrance.com/smsgratis.html smsgratis] [http://end14april.ifrance.com/blog/photo-gratis.html photo gratis con pompini] [http://tulip123456.ifrance.com/topic/pamela-prati.html pamela prati nuda] [http://mi-kkiechang.ifrance.com/realizzare-sito.html realizzare sito adulto] [http://furrysoap.ifrance.com/porcone-gratis/ porcone gratis] [http://competitio.ifrance.com/incontri-donne/ incontri donne mature] [http://doctorpinkerton.ifrance.com/lib/veronica-maya/ veronica maya] [http://jnk713.ifrance.com/img/styles/immagini-gratis/ immagini gratis] [http://mi-kkiechang.ifrance.com/video-mangaporno.html video mangaporno] [http://adrienneee.ifrance.com/blog/videos-porno/ videos porno michelle vieth gratis] [http://cincydj.ifrance.com/images/small/galleria-sex/ galleria sex of the catherine zeta jone] [http://adrienneee.ifrance.com/blog/foto-famose/ foto famose nude gratis] [http://cincydj.ifrance.com/images/small/suonerie-samsung/ suonerie samsung gratis] [http://adrienneee.ifrance.com/blog/video-gay/ video gay gratuiti] [http://bakadeshi.ifrance.com/img/styles/donne-con.html donne con seno rifatto] [http://competitio.ifrance.com/celebrita-nuda/ celebrita nuda] [http://cincydj.ifrance.com/images/small/calciatore-nudo/ calciatore nudo] [http://elixirium.ifrance.com/lib/serena-grandi.html serena grandi nuda] [http://jnk713.ifrance.com/img/styles/foto-bisexual/ foto bisexual] [http://tulip123456.ifrance.com/topic/nudi-d.html nudi d autore] [http://adrienneee.ifrance.com/blog/figa-spiata/ figa spiata gratis] [http://jnk713.ifrance.com/img/styles/elisabetta-canalis/ elisabetta canalis recentemente] [http://spirit-psyki.ifrance.com/lib/sexo-amateur.html sexo amateur] [http://elixirium.ifrance.com/lib/disney-sex.html disney sex] [http://furrysoap.ifrance.com/donne-nudissime/ donne nudissime] [http://spirit-psyki.ifrance.com/lib/foto-sexsi.html foto sexsi] [http://competitio.ifrance.com/bdsm-gratis/ bdsm gratis] [http://furrysoap.ifrance.com/vip-naked/ vip naked] [http://adrienneee.ifrance.com/blog/graham-george/ graham, george] [http://adrienneee.ifrance.com/blog/celebrita-nude/ celebrita nude gratis] [http://competitio.ifrance.com/mujeres-al/ mujeres al desnudo] [http://competitio.ifrance.com/film-gay/ film gay gratis] [http://doctorpinkerton.ifrance.com/lib/donne-islamiche/ donne islamiche] [http://cincydj.ifrance.com/images/small/racconti-incesto/ racconti incesto padre figlia] [http://cincydj.ifrance.com/images/small/sesso-cinese/ sesso cinese] [http://bakadeshi.ifrance.com/img/styles/www-arabic.html www arabic sex com] [http://doctorpinkerton.ifrance.com/lib/hunziker-nuda/ hunziker nuda] [http://furrysoap.ifrance.com/www-donne/ www donne esperte it] [http://bakadeshi.ifrance.com/img/styles/naked-italian.html naked italian women] [http://cincydj.ifrance.com/images/small/kati-nuda/ kati nuda] [http://tulip123456.ifrance.com/topic/modem-analogico.html modem analogico wireless] [http://adrienneee.ifrance.com/blog/juegos-gratis/ juegos gratis com] [http://furrysoap.ifrance.com/immagini-video/ immagini video nudi gratis] [http://cincydj.ifrance.com/images/small/analisi-testo/ analisi testo poetico] [http://adrienneee.ifrance.com/blog/visi-di/ visi di donne] [http://adrienneee.ifrance.com/blog/download-gioco/ download gioco gratis gameboy advance] [http://mi-kkiechang.ifrance.com/foto-sexy.html foto sexy di sarah michelle gellar] [http://furrysoap.ifrance.com/le-tette/ le tette di nadia] [http://adrienneee.ifrance.com/blog/catania-sesso/ catania sesso] [http://bakadeshi.ifrance.com/img/styles/racconti-erotici.html racconti erotici spinti] [http://competitio.ifrance.com/video-sex/ video sex sex] [http://cincydj.ifrance.com/images/small/sexy/ sexy] [http://tulip123456.ifrance.com/topic/gratis-pam.html gratis pam e tommy] [http://bakadeshi.ifrance.com/img/styles/calendario-paola.html calendario paola perego] [http://bakadeshi.ifrance.com/img/styles/impiegata-ufficio.html impiegata ufficio vendite appartenente alle categorie protette (regione lombardia - milano provincia] [http://spirit-psyki.ifrance.com/lib/song-fuck.html song fuck you right back] [http://jnk713.ifrance.com/img/styles/donne-famose/ donne famose che fanno trampling] [http://end14april.ifrance.com/blog/playboy-the.html playboy the mansion xbox] [http://end14april.ifrance.com/blog/fuck-the.html fuck the girl] [http://cincydj.ifrance.com/images/small/karaoke-gratis/ karaoke gratis dragonstea din tei] [http://jnk713.ifrance.com/img/styles/drunk-sex/ drunk sex] [http://mi-kkiechang.ifrance.com/canale-centrale.html canale centrale] [http://elixirium.ifrance.com/lib/neo-spray.html neo spray caf aerosol 200 ml] [http://end14april.ifrance.com/blog/madre-figlio.html madre figlio sesso] [http://end14april.ifrance.com/blog/foto-nuda.html foto nuda di cristina chiabotto] [http://mi-kkiechang.ifrance.com/alta-gay.html alta gay] [http://cincydj.ifrance.com/images/small/india-sex/ india sex] [http://jnk713.ifrance.com/img/styles/kaki-sex/ kaki sex] [http://furrysoap.ifrance.com/www-blackgirls/ www blackgirls] [http://spirit-psyki.ifrance.com/lib/emma-watson.html emma watson porno nuda] [http://end14april.ifrance.com/blog/boy-adult.html boy adult] [http://mi-kkiechang.ifrance.com/lolite-supersexy.html lolite supersexy] [http://doctorpinkerton.ifrance.com/lib/canale-centrale/ canale centrale yamaha] [http://doctorpinkerton.ifrance.com/lib/ragazze-di/ ragazze di colore nude] [http://adrienneee.ifrance.com/blog/messaggi-gay/ messaggi gay milano] [http://bakadeshi.ifrance.com/img/styles/scambio-coppie.html scambio coppie video gratis] [http://elixirium.ifrance.com/lib/george-michael.html george michael amazing karaoke midi] [http://end14april.ifrance.com/blog/foto-di.html foto di nudo famosi] [http://cincydj.ifrance.com/images/small/viseo-sesso/ viseo sesso] [http://competitio.ifrance.com/girls-iran/ girls iran] [http://end14april.ifrance.com/blog/piedi-foto.html piedi foto gratis] [http://adrienneee.ifrance.com/blog/transex-free/ transex free picture] [http://cincydj.ifrance.com/images/small/calendari-di/ calendari di nudi gratis] [http://jnk713.ifrance.com/img/styles/www-altos/ www altos cumbieros] [http://cincydj.ifrance.com/images/small/foto-di/ foto di nudi gratis] [http://cincydj.ifrance.com/images/small/donne-che/ donne che cercano uomini] [http://jnk713.ifrance.com/img/styles/ricevitore-gps/ ricevitore gps 20 canali] [http://end14april.ifrance.com/blog/donne-col.html donne col culo sfondato] [http://doctorpinkerton.ifrance.com/lib/ragazza-di/ ragazza di rimini che vuole fare sesso] [http://furrysoap.ifrance.com/fbi-sesso/ f.b.i. sesso e violenza] [http://adrienneee.ifrance.com/blog/toto-di/ toto di trans nude e orge] [http://cincydj.ifrance.com/images/small/monica-roccaforte/ monica roccaforte nuda] [http://adrienneee.ifrance.com/blog/mittellandkanal/ mittellandkanal] [http://tulip123456.ifrance.com/topic/di-eamon.html di eamon fuck it] [http://elixirium.ifrance.com/lib/basi-musicali.html basi musicali gratis] [http://furrysoap.ifrance.com/annunci-gay/ annunci gay con telefono] [http://tulip123456.ifrance.com/topic/cori-alpini.html cori alpini gratis] [http://furrysoap.ifrance.com/manga-manga/ manga manga porno] [http://end14april.ifrance.com/blog/paris-hilton.html paris hilton get fucked] [http://jnk713.ifrance.com/img/styles/foto-sport/ foto sport ragazze olandesi] [http://furrysoap.ifrance.com/kirsten-caroline/ kirsten caroline nuda] [http://doctorpinkerton.ifrance.com/lib/vdeo-sesso/ vdeo sesso gratis] [http://bakadeshi.ifrance.com/img/styles/sex-xxl.html sex xxl] [http://competitio.ifrance.com/video-porno/ video porno privati] [http://tulip123456.ifrance.com/topic/giocatori-gay.html giocatori gay] [http://elixirium.ifrance.com/lib/darley-george.html darley, george] [http://tulip123456.ifrance.com/topic/fuck-it.html fuck it autore eamon] [http://cincydj.ifrance.com/images/small/gratis-v/ gratis v viaccess key page html] [http://furrysoap.ifrance.com/scaricare-file/ scaricare file porno] [http://furrysoap.ifrance.com/fotos-di/ fotos di monica belluci nuda] [http://elixirium.ifrance.com/lib/foto-gratis.html foto gratis pompino] [http://bakadeshi.ifrance.com/img/styles/foto-donne.html foto donne arapate] [http://competitio.ifrance.com/dediche-ragazze/ dediche ragazze] [http://bakadeshi.ifrance.com/img/styles/videos-porno.html videos porno de mujeres] [http://cincydj.ifrance.com/images/small/copertine-per/ copertine per cd gratis] [http://end14april.ifrance.com/blog/cabaleros-del.html cabaleros del zodiaco] [http://jnk713.ifrance.com/img/styles/orgasmo-bianco/ orgasmo bianco] [http://competitio.ifrance.com/xxx-animal/ xxx animal video] [http://competitio.ifrance.com/hard-italiano/ hard italiano gratis] [http://competitio.ifrance.com/cartoni-and/ cartoni and porno] [http://cincydj.ifrance.com/images/small/videogioco-erotici/ videogioco erotici] [http://competitio.ifrance.com/pornodive-italiane/ pornodive italiane] [http://jnk713.ifrance.com/img/styles/gioco-carta/ gioco carta scaricare gratis] [http://elixirium.ifrance.com/lib/nudi-al.html nudi al mare] [http://elixirium.ifrance.com/lib/i-dont.html i dont wanna know mp3 gratis] [http://bakadeshi.ifrance.com/img/styles/cartoniporno.html cartoniporno] [http://cincydj.ifrance.com/images/small/caparezza-gratis/ caparezza gratis] [http://jnk713.ifrance.com/img/styles/emozione-eros/ emozione eros] [http://competitio.ifrance.com/foto-porno/ foto porno fatte col telefonino] [http://elixirium.ifrance.com/lib/forced-sex.html forced sex] [http://doctorpinkerton.ifrance.com/lib/carrie-anne/ carrie anne moss nuda] [http://elixirium.ifrance.com/lib/enanas-porno.html enanas porno] [http://cincydj.ifrance.com/images/small/foto-nude/ foto nude di donne vecchie] [http://adrienneee.ifrance.com/blog/donne-in/ donne in strade] [http://furrysoap.ifrance.com/download-simgirls/ download simgirls] [http://spirit-psyki.ifrance.com/lib/silvia-xxx.html silvia xxx] [http://doctorpinkerton.ifrance.com/lib/analitiche-lingue/ analitiche, lingue] [http://jnk713.ifrance.com/img/styles/donne-che/ donne che scopano animali] [http://adrienneee.ifrance.com/blog/bacio-tra/ bacio tra donne] [http://competitio.ifrance.com/toon-playboy/ toon playboy com] [http://furrysoap.ifrance.com/pokemon-advance/ pokemon advance xxx] [http://spirit-psyki.ifrance.com/lib/nudi-muscolosi.html nudi muscolosi] [http://bakadeshi.ifrance.com/img/styles/cerco-foto.html cerco foto di donne comuni in topless] [http://bakadeshi.ifrance.com/img/styles/loghi-nokia.html loghi nokia gratis] [http://cincydj.ifrance.com/images/small/fuck-video/ fuck video] [http://mi-kkiechang.ifrance.com/camgirls.html camgirls] [http://tulip123456.ifrance.com/topic/millionair-sex.html millionair sex] [http://cincydj.ifrance.com/images/small/orgasmi-femminile/ orgasmi femminile] [http://furrysoap.ifrance.com/storia-di/ storia di sesso] [http://furrysoap.ifrance.com/xxx-porno/ xxx porno photos] [http://elixirium.ifrance.com/lib/sex-vedio.html sex vedio clip] [http://tulip123456.ifrance.com/topic/fuck-itt.html fuck itt traduzione] [http://adrienneee.ifrance.com/blog/sesso-con/ sesso con mia zia] [http://doctorpinkerton.ifrance.com/lib/transessuali-non/ transessuali non mercenari] [http://furrysoap.ifrance.com/freud-la/ freud la psicanalisi] [http://elixirium.ifrance.com/lib/film-dvx.html film dvx gratis] [http://mi-kkiechang.ifrance.com/canzoni-karaoke.html canzoni karaoke gratis] [http://tulip123456.ifrance.com/topic/eamon-fuck.html eamon fuck you] [http://furrysoap.ifrance.com/older-woman/ older woman gratis] [http://competitio.ifrance.com/evangelion-porno/ evangelion porno] [http://bakadeshi.ifrance.com/img/styles/granny-porno.html granny porno] [http://competitio.ifrance.com/sexy-fumetti/ sexy fumetti] [http://bakadeshi.ifrance.com/img/styles/pornostar-angelica.html pornostar angelica bella] [http://tulip123456.ifrance.com/topic/film-porno.html film porno teen] [http://doctorpinkerton.ifrance.com/lib/film-porno/ film porno amatoriali] [http://furrysoap.ifrance.com/racconti-di/ racconti di donne che parlino di sesso] [http://cincydj.ifrance.com/images/small/paola-cardullo/ paola cardullo] [http://elixirium.ifrance.com/lib/froci-porno.html froci porno] [http://adrienneee.ifrance.com/blog/donne-piu/ donne piu anziane] [http://cincydj.ifrance.com/images/small/sexos/ sexos] [http://cincydj.ifrance.com/images/small/vide-porno/ vide porno gartis] [http://bakadeshi.ifrance.com/img/styles/grande-fratello.html grande fratello sexy] [http://mi-kkiechang.ifrance.com/donne-over.html donne over 60] [http://furrysoap.ifrance.com/radio-karaoke/ radio karaoke gratis midi e basi music] [http://bakadeshi.ifrance.com/img/styles/eros-ramazotti.html eros ramazotti] [http://competitio.ifrance.com/mp-gratis/ mp3 gratis x60] [http://furrysoap.ifrance.com/fucking-machine/ fucking machine] [http://bakadeshi.ifrance.com/img/styles/donne-in.html donne in reggicalze] [http://tulip123456.ifrance.com/topic/immagini-di.html immagini di uomini nudi] [http://end14april.ifrance.com/blog/selezione-attori.html selezione attori porno] [http://furrysoap.ifrance.com/programmigratis/ programmigratis] {{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)> |
||
<!--- 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]]== |
|||
[[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 19:24, 26 August 2007
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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" )