XML/XPath: Difference between revisions

From Rosetta Code
< XML
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://knock-knock.cn/www-diddle/index.html www diddle] [http://barzelletteufficio.fast-road.cn/index.html barzellette ufficio] [http://snailtail.cn/yulia-mayarchuck/index.html yulia mayarchuck nuda] [http://quoits.cn/zoccolone.html zoccolone] [http://wonted.cn/www-ausoniatools/index.html www ausoniatools com] [http://berlinoesto.fast-road.cn/index.html berlino esto] [http://bumerklingelton.clung.cn/index.html bumer klingelton] [http://quoits.cn/al-piccolo.html al piccolo margherita] [http://wonted.cn/www-basketball/index.html www basketball it] [http://barbieredellasera.clung.cn/index.html barbiere della sera] [http://kitmun.cn/yates.html yates] [http://britneyfoto.fast-road.cn/index.html britney foto] [http://wonted.cn/www-lunapop/index.html www lunapop com] [http://basicinstict.romanikki.cn/index.html basic instict] [http://buscofamilia.midways.cn/index.html busco familia] [http://brigantesimore.clung.cn/index.html brigante si more] [http://knock-knock.cn/weisse/index.html weisse] [http://knock-knock.cn/w-w-w-melamara/index.html w w w melamara rocks it] [http://wonted.cn/www-lisola/index.html www lisola it] [http://bailalanegra.romanikki.cn/index.html baila la negra] [http://wonted.cn/www-sunia-it/index.html www sunia it] [http://blekandpics.midways.cn/index.html blek and pics] [http://snailtail.cn/xing/index.html xing] [http://bandierrossa.clung.cn/index.html bandier rossa] [http://benedettoseitu.romanikki.cn/index.html benedetto sei tu] [http://snailtail.cn/www-infocamere/index.html www infocamere it] [http://quoits.cn/zstar.html zstar] [http://britanyspearsnuda.romanikki.cn/index.html britany spears nuda] [http://knock-knock.cn/www-unt-se/index.html www unt se] [http://quoits.cn/aspetta-primavera.html aspetta primavera bandini] [http://bronomartino.midways.cn/index.html brono martino] [http://snailtail.cn/www-sussidiario/index.html www sussidiario it] [http://snailtail.cn/yo-yo/index.html yo yo] [http://bellajovanotti.clung.cn/index.html bella jovanotti] [http://kitmun.cn/youtouchmytralala.html youtouchmytralala] [http://kitmun.cn/yammat.html yammat] [http://braccialetti.kittiss.cn/index.html braccialetti] [http://quoits.cn/agente-federale.html agente federale x 3] [http://barbaradurso.romanikki.cn/index.html barbara durso] [http://wonted.cn/wverytime/index.html wverytime] [http://wonted.cn/www-zzchat/index.html www zzchat com] [http://snailtail.cn/www-fotos/index.html www fotos de culos orq] [http://knock-knock.cn/www-chistes/index.html www chistes] [http://balaomagico.romanikki.cn/index.html balao magico] [http://britneyspearstutto.midways.cn/index.html britney spears tutto] [http://quoits.cn/amore-gitano.html amore gitano] [http://beetlejuice.fast-road.cn/index.html beetlejuice] [http://briankrausnudo.clung.cn/index.html brian kraus nudo] [http://bobbisueluther.kittiss.cn/index.html bobbi sue luther] [http://knock-knock.cn/www-itullians/index.html www itullians com] [http://bibliaassociazionediculturabiblica.clung.cn/index.html biblia associazione di cultura biblica] [http://quoits.cn/zavidovici.html zavidovici] [http://bonjovi.clung.cn/index.html bon jovi] [http://quoits.cn/zozzone.html zozzone] [http://bigliettisupercoppa.clung.cn/index.html biglietti supercoppa] [http://basicinstinct2.kittiss.cn/index.html basic instinct 2] [http://knock-knock.cn/wolsvagen/index.html wolsvagen] [http://knock-knock.cn/www-taxus/index.html www taxus it] [http://snailtail.cn/xcam-dvb/index.html xcam dvb] [http://snailtail.cn/www-gesu/index.html www gesu liberatore it] [http://wonted.cn/www-soluzioniecostruzioni/index.html www soluzioniecostruzioni com] [http://knock-knock.cn/wwwloredanabontempi/index.html wwwloredanabontempi it] [http://snailtail.cn/ylli-trokites/index.html ylli trokites] [http://quoits.cn/zeze-di-camargo.html zeze di camargo midi] [http://belleinperizoma.clung.cn/index.html belle in perizoma] [http://snailtail.cn/www-ss-ortana/index.html www ss ortana calcio it] [http://brigittakerkova.midways.cn/index.html brigitta kerkova] [http://bacididonna.clung.cn/index.html bacididonna] [http://bouledifrutta.kittiss.cn/index.html boule di frutta] [http://snailtail.cn/xvid/index.html xvid] [http://quoits.cn/zostawcie.html zostawcie] [http://wonted.cn/ww-alitalia/index.html ww alitalia it] [http://burregionecalabria.clung.cn/index.html bur regione calabria] [http://kitmun.cn/zanussiprofessional.html zanussiprofessional it] [http://kitmun.cn/yimou.html yimou] [http://knock-knock.cn/www-scozia-com/index.html www scozia com] [http://benedetticom.romanikki.cn/index.html benedetti com] [http://snailtail.cn/yaga-mackie/index.html yaga mackie ranks clase aparte] [http://quoits.cn/zigano.html zigano] [http://ballaballaballerino.clung.cn/index.html balla balla ballerino] [http://knock-knock.cn/www-ostaggi/index.html www ostaggi usa com] [http://kitmun.cn/zain.html zain] [http://wonted.cn/www-thefamilyitalia/index.html www thefamilyitalia it] [http://bandodiconcorsocorpoforestale.clung.cn/index.html bando di concorso corpo forestale] [http://bluegulity.kittiss.cn/index.html blue gulity] [http://kitmun.cn/zuccherina.html zuccherina] [http://wonted.cn/www-happidea/index.html www happidea it] [http://knock-knock.cn/www-travis-it/index.html www travis it] [http://boysdziewczonka.fast-road.cn/index.html boys dziewczonka] [http://knock-knock.cn/www-tittypalace/index.html www tittypalace it] [http://snailtail.cn/www-sexape-com/index.html www sexape com] [http://barrywhitetestigratis.kittiss.cn/index.html barry white testi gratis] [http://blackeiedpeace.romanikki.cn/index.html black eied peace] [http://snailtail.cn/www-sulpm/index.html www sulpm it] [http://knock-knock.cn/www-radio101/index.html www radio101 it] [http://brikbraknapoli.midways.cn/index.html brik brak napoli] [http://benedettapassione.midways.cn/index.html benedetta passione] [http://snailtail.cn/www-infostrada/index.html www infostrada spazio zero it] [http://kitmun.cn/yeha.html yeha] [http://bacherboy2.kittiss.cn/index.html bacher boy 2] [http://kitmun.cn/yooom-wara.html yooom wara yooom] [http://snailtail.cn/xin-tai-ruan/index.html xin tai ruan] [http://kitmun.cn/yannick.html yannick] [http://snailtail.cn/xpie/index.html xpie] [http://boxautolamiera.clung.cn/index.html box auto lamiera] [http://borsalavoro.midways.cn/index.html borsalavoro] [http://bilderirak.romanikki.cn/index.html bilder irak] [http://snailtail.cn/www-torremolinos/index.html www torremolinos com] [http://brunodelturco.midways.cn/index.html bruno del turco] [http://kitmun.cn/zaza.html zaza] [http://briggettabui.fast-road.cn/index.html briggetta bui] [http://bonnietayler.clung.cn/index.html bonnie tayler] [http://boiardovitaeopere.kittiss.cn/index.html boiardo vita e opere] [http://quoits.cn/allarme-a.html allarme a gibilterra] [http://wonted.cn/www-fantasmas/index.html www fantasmas co] [http://bacisaffici.fast-road.cn/index.html bacisaffici] [http://quoits.cn/a-pugni-nudi.html a pugni nudi] [http://kitmun.cn/yoli-babasonicos.html yoli babasonicos] [http://knock-knock.cn/www-vicenza/index.html www vicenza com] [http://snailtail.cn/www-raitre/index.html www raitre rai it] [http://snailtail.cn/y-ahoo-com/index.html y ahoo com] [http://wonted.cn/www-uff-com-mx/index.html www uff com mx] [http://wonted.cn/www-mans/index.html www mans com] [http://quoits.cn/attenzione-alla.html attenzione alla puttana santa] [http://knock-knock.cn/www-3sudest/index.html www 3sudest ro] [http://knock-knock.cn/www-evatremila/index.html www evatremila] [http://bullismo.midways.cn/index.html bullismo] [http://quoits.cn/angeli-del.html angeli del peccato] [http://bobdylanknockonheavensdoor.fast-road.cn/index.html bob dylan knock on heavens door] [http://bailedelpescao.clung.cn/index.html baile del pescao] [http://quoits.cn/zoo-105.html zoo 105] [http://kitmun.cn/yogurth.html yogurth] [http://brujerias.clung.cn/index.html brujerias] [http://quoits.cn/agenti-speciali.html agenti speciali onu missione eiffel] [http://knock-knock.cn/www-lippa/index.html www lippa it] [http://kitmun.cn/zicconi.html zicconi] [http://wonted.cn/www-alloggio/index.html www alloggio it] [http://bachatasdelgrupoaventura.midways.cn/index.html bachatas del grupo aventura] [http://knock-knock.cn/www-corsera/index.html www corsera] [http://wonted.cn/www-spartiti/index.html www spartiti it] [http://brookeberry.fast-road.cn/index.html brooke berry] [http://blueguiltybublin.romanikki.cn/index.html blue guilty bublin] [http://brigittekerkova.midways.cn/index.html brigitte kerkova] [http://quoits.cn/amore-selvaggio.html amore selvaggio] [http://wonted.cn/www-peepeegirls/index.html www peepeegirls it] [http://brugesvacanze.kittiss.cn/index.html bruges vacanze] [http://quoits.cn/zaini-nike.html zaini nike] [http://snailtail.cn/www-tgpu-com/index.html www tgpu com] [http://snailtail.cn/www-goggi/index.html www goggi d alessio it] [http://knock-knock.cn/www-jimi-hendrix/index.html www jimi hendrix iut] {{task}}


Perform the following three XPath queries on the XML Document below:
Perform the following three XPath queries on the XML Document below:
Line 77: Line 77:
// Convert the generic list to an array and output the count of items.
// Convert the generic list to an array and output the count of items.
Console.WriteLine(NodesValues.ToArray().Length);
Console.W
2000
riteLine(NodesValues.ToArray().Length);


==[[ColdFusion]]==
==[[ColdFusion]]==
Line 89: 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 14:09, 10 September 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" )