XML/XPath: Difference between revisions
< XML
Content added Content deleted
mNo edit summary |
(revert spam) |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://hewvey.ifrance.com/library/konica-minolta/ konica minolta flash] [http://jrosestar.ifrance.com/html/paul-oakenfold/ paul oakenfold] [http://dylantian.ifrance.com/styles/obsesion-radio.htm obsesion radio mix] [http://spkleins.angelfire.com/todo-de/ todo de porno] [http://feralpaw-omm.ifrance.com/html/codici-per/ codici per carte titanium] [http://macertot.ifrance.com/view/motoseghe-da.htm motoseghe da potatura] [http://jrosestar.ifrance.com/html/the-roxy/ the roxy music blondie] [http://isabellaval.ifrance.com/driver-scheda/ driver scheda rete] [http://feralpaw-omm.ifrance.com/html/employment-in/ employment in the uk] [http://kataevka.ifrance.com/articles/corrado-alvaro/ corrado alvaro] [http://yvharlen.at.tut.by/lib/filodoro.htm filodoro] [http://brandalinden.ifrance.com/topic/ninne-nanna.htm ninne nanna italiane] [http://mckueltzi.at.tut.by/description/lib/l-iperbole.htm l iperbole] [http://nymphbmbzl222.ifrance.com/hail.htm hail] [http://jrosestar.ifrance.com/html/plane-tickets/ plane tickets] [http://wipitts.at.tut.by/text/directory/desktop-offerta.htm desktop offerta] [http://jrosestar.ifrance.com/html/hd-firewire/ hd firewire 800] [http://konstantinkar.ifrance.com/description/dual-input/ dual input monitor] [http://seedging.at.tut.by/text/directory/salassa.htm salassa] [http://nymphbmbzl222.ifrance.com/la-ultima.htm la ultima vez] [http://konstantinkar.ifrance.com/description/www-lil/ www lil games com] [http://ariadnafeni.ifrance.com/resources/olivetti-fax/ olivetti fax lab] [http://wipitts.at.tut.by/text/directory/siemens-mg.htm siemens m1437g] [http://spkleins.angelfire.com/xanga-skins/ xanga skins] [http://alena344.ifrance.com/text/software-fattura/ software fattura] [http://spkleins.angelfire.com/spartiti-musicali/ spartiti musicali canzoni napoletane] [http://feralpaw-omm.ifrance.com/html/comune-pesaro/ comune pesaro] [http://nymphbmbzl222.ifrance.com/offerta-copenhagen.htm offerta copenhagen] [http://agodichik.angelfire.com/styles/randfichten-lebt.htm randfichten lebt denn dr alte holzmichel] [http://kataevka.ifrance.com/articles/z/ z3 1 8] [http://habeard.angelfire.com/topic/fumetti-erotici.htm fumetti erotici gtatuiti] [http://kibrumfik.at.tut.by/text/directory/concerti-per.htm concerti per regione] [http://feralpaw-omm.ifrance.com/html/abe-win/ abe win] [http://dweejah.ifrance.com/new/maglie-guess/ maglie guess donna abbigliamento] [http://wifry.angelfire.com/styles/barolo-voerzio.htm barolo voerzio] [http://beyonddreamingx.angelfire.com/content/ospedale-maggiore.htm ospedale maggiore bologna] [http://kairikekui.ifrance.com/resources/dana-ferrara/ dana ferrara] [http://kibrumfik.at.tut.by/text/directory/www-basi.htm www basi musica it] [http://kairikekui.ifrance.com/resources/film-porrno/ film porrno di carmen russo] [http://zaweaver.at.tut.by/text/directory/hoostabank-mp.htm hoostabank mp3] [http://feralpaw-omm.ifrance.com/html/milano-chat/ milano chat] [http://emstripl.at.tut.by/view/new/autoradio-cd.htm autoradio cd mp3 usb] [http://brandalinden.ifrance.com/topic/la-passeggiata.htm la passeggiata] [http://snerma.angelfire.com/text/sony-/ sony dcrhc90] [http://kairikekui.ifrance.com/resources/scuole-alliste/ scuole alliste] [http://hewvey.ifrance.com/library/e-lucevan/ e lucevan le stelle] [http://agodichik.angelfire.com/styles/torta-meringata.htm torta meringata] [http://agodichik.angelfire.com/styles/comune-di.htm comune di cannobbio it] [http://stdamin.at.tut.by/html/sting-brand.htm sting brand new day tour live from universal amphitheatre] [http://nymphbmbzl222.ifrance.com/emiro-reggio.htm emiro reggio emilia] [http://dylantian.ifrance.com/styles/unikkatil.htm unikkatil] [http://nymphbmbzl222.ifrance.com/f-live.htm f1 live] [http://jrosestar.ifrance.com/html/incontro-sant/ incontro sant] [http://ariadnafeni.ifrance.com/resources/oceans-boxset/ oceans boxset] [http://sagaddy.angelfire.com/styles/spinete/ spinete] [http://isabellaval.ifrance.com/domiciliazione-postale/ domiciliazione postale] [http://kataevka.ifrance.com/articles/cuatro-rosas/ cuatro rosas de jorge celedon] [http://kairikekui.ifrance.com/resources/matrixcam-reloaded/ matrixcam reloaded] [http://casloan.angelfire.com/small/batteria-videocamera/ batteria videocamera panasonic] [http://kataevka.ifrance.com/articles/mayure/ mayure] [http://nymphbmbzl222.ifrance.com/di-ross.htm di ross] [http://macertot.ifrance.com/view/borsoni-pelle.htm borsoni pelle] [http://kataevka.ifrance.com/articles/wind-modena/ wind modena] [http://pohogue.angelfire.com/library/cartoon.htm cartoon 69] [http://wowinoth.at.tut.by/web/sem-limite.htm sem limite pra sonhar] [http://mckueltzi.at.tut.by/description/lib/www-uproar.htm www uproar com] [http://jrosestar.ifrance.com/html/televisori-/ televisori 100 hertz] [http://nymphbmbzl222.ifrance.com/could-place.htm could place] [http://konstantinkar.ifrance.com/description/brucelee/ brucelee] [http://hewvey.ifrance.com/library/la-petroniana/ la petroniana] [http://rebuckma.angelfire.com/description/gioco-demo.htm gioco demo pc] [http://crhighto.at.tut.by/img/styles/bouquet-sposa.htm bouquet sposa] [http://lasylvan.angelfire.com/new/tv-per/ tv per auto dvd lettori e divx] [http://wowinoth.at.tut.by/web/rivista-gq.htm rivista gq] [http://konstantinkar.ifrance.com/description/office-per/ office per mac 2004 italiano] [http://jrosestar.ifrance.com/html/this-love/ this love maroon 5] [http://wifry.angelfire.com/styles/mp-i.htm mp3 i mode] [http://macertot.ifrance.com/view/guida-al.htm guida al campionato] [http://casloan.angelfire.com/small/antonello-de/ antonello de pierro isola dei famosi] [http://jrosestar.ifrance.com/html/sin-bandera/ sin bandera midi] [http://brandalinden.ifrance.com/topic/mistral-gagnant.htm mistral gagnant] [http://dylantian.ifrance.com/styles/satellite-a.htm satellite a80131] [http://grsaltrie.at.tut.by/text/directory/morr.htm morr] [http://kataevka.ifrance.com/articles/lcd-computer/ lcd computer] [http://snerma.angelfire.com/text/pj-tx/ pj tx100] [http://wipitts.at.tut.by/text/directory/na-zawsze.htm na zawsze oboz ta] [http://alena344.ifrance.com/text/sono-un/ sono un italiano vero] [http://thmastrie.angelfire.com/resources/scheda-computer.htm scheda computer firewire] [http://konstantinkar.ifrance.com/description/some-might/ some might say] [http://seedging.at.tut.by/text/directory/jo-quiero.htm jo quiero bailar] [http://feralpaw-omm.ifrance.com/html/the-shark/ the shark] [http://brandalinden.ifrance.com/topic/flaviana.htm flaviana] [http://isabellaval.ifrance.com/renato-e/ renato e i profeti] [http://lehartfi.at.tut.by/lib/note-di.htm note di natale] [http://mckueltzi.at.tut.by/description/lib/she-wille.htm she wille be loved] [http://alena344.ifrance.com/text/voli-caorle/ voli caorle] [http://thmastrie.angelfire.com/resources/patch-update.htm patch update gioco] [http://brandalinden.ifrance.com/topic/storia-turismo.htm storia turismo] [http://gaburlei.angelfire.com/resources/i-pirati.htm i pirati della malesia] [http://kataevka.ifrance.com/articles/deumidificatore-tasciugo/ deumidificatore tasciugo] [http://www-locman.taliabriscoe.cn www locman it] [http://web-sorting.cn/videoclips-de.htm videoclips de musica] [http://zara-croazia.panzerfausts.com.cn zara croazia] [http://nonkomformist.cn/raffy.htm raffy] [http://fierydarknez.cn/equus.htm equus] [http://circhi-a.greylopht.cn circhi a roma] [http://s-benedetto.digirb-backward.cn s benedetto] [http://www.digirb-backward.cn www 2 pac com] [http://fierydarknez.cn/madre-figlio.htm madre figlio sesso] [http://nadzor-ns.cn/water-bed.htm water bed sheet] [http://pixie-bite.org.cn/ddr.htm ddr 256] [http://bella-bellissima.greylopht.cn bella bellissima] [http://nonkomformist.cn/hyundai-lcd.htm hyundai lcd 17 l72s] [http://cartel-del.greylopht.cn cartel del santa] [http://seat-altea.panzerfausts.com.cn seat altea km zero] [http://sex-movi.mack-si.cn sex movi] [http://hunt-red.jowugow.cn hunt red october] [http://keokepa.com.cn/lan-chile.htm lan chile] [http://dustybooks.cn/frigoriferi-combinati.htm frigoriferi combinati da incasso] [http://waltermoney.cn/decapitazione-jhonson.htm decapitazione jhonson] [http://georgiil.net.cn/vendita-dvd.htm vendita dvd online] [http://nonkomformist.cn/invito-compleanno.htm invito compleanno] [http://dustybooks.cn/il-cacciatore.htm il cacciatore nel bosco] [http://luise-ullrich.taliabriscoe.cn luise ullrich] [http://georgiil.net.cn/nikon-d.htm nikon d50 1855 55200] [http://dvd-washer.mack-si.cn dvd washer] [http://photo.taliabriscoe.cn photo 75 studio fotografico] [http://jazz-davide.taliabriscoe.cn jazz davide sparti] [http://robbie-williams.taliabriscoe.cn robbie williams sul pc] [http://milano-berlino.greylopht.cn milano berlino] [http://nadzor-ns.cn/nessun-accordo.htm nessun accordo fra bluray e hddvd] [http://nonkomformist.cn/annuncio-affitti.htm annuncio affitti vicenza] [http://web-sorting.cn/nike-silver.htm nike silver air max wmns] [http://knuckles-lives.cn/oki.htm oki 3200] [http://dustybooks.cn/aspirapolvere-professionale.htm aspirapolvere professionale] [http://figure-geometriche.taliabriscoe.cn figure geometriche] [http://pixie-bite.org.cn/supereva-com.htm supereva com] [http://terme-di.kiushapo.cn terme di cola] [http://chris-liebing.happi-thoughts.org.cn chris liebing] [http://giochi-preziosi.digirb-backward.cn giochi preziosi] [http://nonkomformist.cn/creative-soundworks.htm creative soundworks] [http://la-vergine.happi-thoughts.org.cn la vergine e la bestia] [http://waltermoney.cn/videocamera-digitale.htm videocamera digitale panasonic nv gs] [http://nadzor-ns.cn/viareggio-alberghi.htm viareggio alberghi] [http://yaesu-vx.taliabriscoe.cn yaesu vx] [http://charisse-verhaert.greylopht.cn charisse verhaert] [http://vp-d.greylopht.cn vp d453] [http://nonkomformist.cn/texasville.htm texasville] [http://foto-porno.greylopht.cn foto porno di gay con animali] [http://dlink-print.digirb-backward.cn dlink print] [http://knuckles-lives.cn/escape-from.htm escape from underground] [http://knuckles-lives.cn/jilli.htm jilli] [http://nadzor-ns.cn/ettinger-max.htm ettinger max] [http://knuckles-lives.cn/saab-.htm saab 900 20i turbo 16v 5p s] [http://banane-e.greylopht.cn banane e lamponi] [http://fierydarknez.cn/nikon-mm.htm nikon 70200mm f 2 8] [http://georgiil.net.cn/magnex-lettore.htm magnex lettore mp3] [http://web-sorting.cn/giochi-play.htm giochi play statyon] [http://fierydarknez.cn/www-mondadori.htm www mondadori it] [http://agenzia-entrata.happi-thoughts.org.cn agenzia entrata it] [http://volvo-summum.digirb-backward.cn volvo summum] [http://ebo.digirb-backward.cn ebo] [http://vestire-qualcuno.greylopht.cn vestire qualcuno] [http://fierydarknez.cn/film-porno.htm film porno del giorno] [http://mental-as.fast-girl.net.cn mental as anything basemental] [http://x-file.jowugow.cn x file resist or serve] [http://deskjet.sound-of-sun.cn deskjet 3845] [http://usb-digitale.taliabriscoe.cn usb digitale terrestre terratec] [http://leone-il.happi-thoughts.org.cn leone il cane fifone] [http://nonkomformist.cn/zoom-ottico.htm zoom ottico 12x] [http://fierydarknez.cn/albergo-riva.htm albergo riva del garda] [http://web-sorting.cn/net-magic.htm net magic] [http://nadzor-ns.cn/pecore.htm pecore] [http://grande-frattello.fast-girl.net.cn grande frattello 5] [http://waltermoney.cn/sesso-in.htm sesso in austria] [http://fierydarknez.cn/navigatore-garmin.htm navigatore garmin gps 12] [http://nonkomformist.cn/musica-di.htm musica di natale] [http://pixie-bite.org.cn/jameli.htm jameli] [http://nadzor-ns.cn/hans-zimmer.htm hans zimmer lisa gerrard now we are fre] [http://interfaccia-infrarosso.jowugow.cn interfaccia infrarosso polar] [http://keokepa.com.cn/samsung-lcd.htm samsung lcd 19 913n] [http://keokepa.com.cn/casting-moda.htm casting moda] [http://keokepa.com.cn/messale-liturgico.htm messale liturgico settembre] [http://knuckles-lives.cn/video-email.htm video email] [http://knuckles-lives.cn/biancuzzi.htm biancuzzi] [http://lo-squalo.digirb-backward.cn lo squalo bianco] [http://dustybooks.cn/caldaie-lamborghini.htm caldaie lamborghini] [http://cerca-lavoro.taliabriscoe.cn cerca lavoro mantova] [http://castellana-grotte.sound-of-sun.cn castellana grotte] [http://lettore-dvddivx.happi-thoughts.org.cn lettore dvddivx amstrad] [http://dustybooks.cn/cronache-marziane.htm cronache marziane 15 04 2005] [http://mio-gas.fast-girl.net.cn mio gas san giuliano milanese] [http://waltermoney.cn/racconi-incestuosi.htm racconi incestuosi] [http://mobile-drive.kiushapo.cn mobile drive porsche 80gb] [http://copkiller.fast-girl.net.cn copkiller] [http://nonkomformist.cn/codici-sblocco.htm codici sblocco cellulari lg] [http://cavo-usb.fast-girl.net.cn cavo usb rca] [http://waltermoney.cn/reggiseno-solo.htm reggiseno solo coppe] [http://powermust.panzerfausts.com.cn powermust 600 plus] [http://tv-al.jowugow.cn tv al plasma 17] {{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 12:42, 8 September 2007
XML/XPath
You are encouraged to solve this task according to the task description, using any language you may know.
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" )