XML/XPath: Difference between revisions
Content added Content deleted
(added Haskell (without using specialized modules)) |
m (Fixed lang tags.) |
||
Line 35: | Line 35: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
With regular expressions |
With regular expressions |
||
<lang AutoHotkey> |
<lang AutoHotkey>FileRead, inventory, xmlfile.xml |
||
FileRead, inventory, xmlfile.xml |
|||
RegExMatch(inventory, "<item.*?</item>", item1) |
RegExMatch(inventory, "<item.*?</item>", item1) |
||
Line 47: | Line 46: | ||
While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1) |
While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1) |
||
names .= name . "`n" |
names .= name . "`n" |
||
MsgBox % names |
MsgBox % names</lang> |
||
</lang> |
|||
{{libheader|AHK XPath}} |
{{libheader|AHK XPath}} |
||
<lang AutoHotkey> |
<lang AutoHotkey>#Include xpath.ahk |
||
#Include xpath.ahk |
|||
xpath_load(doc, "xmlfile.xml") |
xpath_load(doc, "xmlfile.xml") |
||
Line 65: | Line 62: | ||
; Get an array of all the "name" elements |
; Get an array of all the "name" elements |
||
MsgBox % xpath(doc, "/inventory/section/item/name") |
MsgBox % xpath(doc, "/inventory/section/item/name")</lang> |
||
</lang> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
<lang csharp> |
<lang csharp>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);</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
<lang |
<lang cpp>#include <vector> |
||
#include <string> |
#include <string> |
||
#include <iostream> |
#include <iostream> |
||
Line 174: | Line 170: | ||
std::copy( names.begin( ) , names.end( ) , std::ostream_iterator<std::string>( std::cout , "\n" )) ; |
std::copy( names.begin( ) , names.end( ) , std::ostream_iterator<std::string>( std::cout , "\n" )) ; |
||
return 0 ; |
return 0 ; |
||
}</lang> |
|||
} |
|||
</lang> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
<lang cfm><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#"></lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
It is important to note that the KXML library currently only supports XPath minimally. |
It is important to note that the KXML library currently only supports XPath minimally. |
||
{{libheader|KXML}} |
{{libheader|KXML}} |
||
<lang d> |
<lang d>import kxml.xml; |
||
import kxml.xml; |
|||
char[]xmlinput = |
char[]xmlinput = |
||
"<inventory title=\"OmniCorp Store #45x10^3\"> |
"<inventory title=\"OmniCorp Store #45x10^3\"> |
||
Line 240: | Line 234: | ||
} |
} |
||
auto namearray = root.parseXPath("inventory/section/item/name"); |
auto namearray = root.parseXPath("inventory/section/item/name"); |
||
}</lang> |
|||
} |
|||
</lang> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Line 279: | Line 271: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
{{works with|Firefox|2.0}} |
{{works with|Firefox|2.0}} |
||
<lang javascript> |
<lang javascript>//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 );</lang> |
|||
Although some browsers support XPath, working with XML is much easier with E4X. |
Although some browsers support XPath, working with XML is much easier with E4X. |
||
<lang javascript> |
<lang javascript>//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 );</lang> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
{{libheader|XML::XPath}} |
{{libheader|XML::XPath}} |
||
<lang perl> |
<lang 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;</lang> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
<lang php> |
<lang php><?php |
||
//PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0) |
|||
<?php |
|||
$doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>'); |
|||
//PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0) |
|||
$doc = DOMDocument:: |
//Load from file instead with $doc = DOMDocument::load('filename'); |
||
$xpath = new DOMXPath($doc); |
|||
//Load from file instead with $doc = DOMDocument::load('filename'); |
|||
/* |
|||
$xpath = new DOMXPath($doc); |
|||
1st Task: Retrieve the first "item" element |
|||
/* |
|||
*/ |
|||
1st Task: Retrieve the first "item" element |
|||
$nodelist = $xpath->query('//item'); |
|||
*/ |
|||
$result = $nodelist->item(0); |
|||
/* |
|||
$result = $nodelist->item(0); |
|||
2nd task: Perform an action on each "price" element (print it out) |
|||
/* |
|||
*/ |
|||
2nd task: Perform an action on each "price" element (print it out) |
|||
$nodelist = $xpath->query('//price'); |
|||
*/ |
|||
for($i = 0; $i < $nodelist->length; $i++) |
|||
$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"; |
|||
//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 |
|||
/* |
|||
*/ |
|||
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 |
|||
$nodelist = $xpath->query('//name'); |
|||
$result = array(); |
|||
//our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList |
|||
//a different way of iterating through the DOMNodeList |
|||
$result = array(); |
|||
foreach($nodelist as $node) |
|||
//a different way of iterating through the DOMNodeList |
|||
{ |
|||
foreach($nodelist as $node) |
|||
$result[] = $node; |
|||
{ |
|||
}</lang> |
|||
$result[] = $node; |
|||
} |
|||
</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
<lang python> |
<lang python># Python has basic xml parsing built in |
||
# Python has basic xml parsing built in |
|||
from xml.dom import minidom |
from xml.dom import minidom |
||
Line 390: | Line 379: | ||
# 3rd Task: Get an array of all the "name" elements |
# 3rd Task: Get an array of all the "name" elements |
||
namesArray = xmldoc.getElementsByTagName("name") |
namesArray = xmldoc.getElementsByTagName("name")</lang> |
||
</lang> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
{{libheader|XML (R)}} |
{{libheader|XML (R)}} |
||
<lang R>## Require the XML package you can download from http://www.omegahat.org/RSXML/ |
|||
<lang R> |
|||
## Require the XML package you can download from http://www.omegahat.org/RSXML/ |
|||
library("XML") |
library("XML") |
||
doc <- xmlInternalTreeParse("test3.xml") |
doc <- xmlInternalTreeParse("test3.xml") |
||
Line 405: | Line 392: | ||
for(i in 1:length(prices)) print(prices[i]) |
for(i in 1:length(prices)) print(prices[i]) |
||
# 3rd Task: Get an array of all the "name" elements |
# 3rd Task: Get an array of all the "name" elements |
||
(namesArray <- sapply(getNodeSet(doc, "//name"), xmlValue)) |
(namesArray <- sapply(getNodeSet(doc, "//name"), xmlValue))</lang> |
||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{libheader|REXML}} |
{{libheader|REXML}} |
||
<lang ruby> |
<lang 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" )</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 436: | Line 421: | ||
better show the results. |
better show the results. |
||
<lang scala>scala> val xml = <inventory title="OmniCorp Store #45x10^3"> |
|||
<lang scala> |
|||
scala> val xml = <inventory title="OmniCorp Store #45x10^3"> |
|||
| <section name="health"> |
| <section name="health"> |
||
| <item upc="123456789" stock="12"> |
| <item upc="123456789" stock="12"> |
||
Line 516: | Line 500: | ||
scala> val values = xml \\ "name" map (_ text) toArray |
scala> val values = xml \\ "name" map (_ text) toArray |
||
values: Array[String] = Array(Invisibility Cream, Levitation Salve, Blork and Freen Instameal, Grob winglets) |
values: Array[String] = Array(Invisibility Cream, Levitation Salve, Blork and Freen Instameal, Grob winglets)</lang> |
||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 538: | Line 521: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
<lang vbnet>Dim first_item = xml.XPathSelectElement("//item") |
|||
Console.WriteLine(first_item) |
|||
For Each price In xml.XPathSelectElements("//price") |
|||
Console.WriteLine(price.Value) |
|||
Next |
|||
Dim names = (From item In xml.XPathSelectElements("//name") Select item.Value).ToArray</lang> |
|||
=={{header|XQuery}}== |
=={{header|XQuery}}== |
||
<lang xquery> |
<lang xquery>(: |
||
(: |
|||
1. Retrieve the first "item" element |
1. Retrieve the first "item" element |
||
Notice the braces around //item. This evaluates first all item elements and then retrieving the first one. |
Notice the braces around //item. This evaluates first all item elements and then retrieving the first one. |
||
Line 569: | Line 550: | ||
<prices>{$price}</prices> |
<prices>{$price}</prices> |
||
<names>{$names}</names> |
<names>{$names}</names> |
||
</result> |
</result></lang> |
||
</lang> |
|||
Performing this XQuery on the given input document results in |
Performing this XQuery on the given input document results in |
||
<lang xquery><?xml version="1.0" encoding="UTF-8"?> |
|||
<lang> |
|||
<?xml version="1.0" encoding="UTF-8"?> |
|||
<result> |
<result> |
||
<firstItem> |
<firstItem> |
||
Line 590: | Line 569: | ||
<name>Grob winglets</name> |
<name>Grob winglets</name> |
||
</names> |
</names> |
||
</result> |
</result></lang> |
||
</lang> |
|||
=={{header|XSLT}}== |
=={{header|XSLT}}== |
||
<lang xml><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
|||
<pre><nowiki> |
|||
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
|||
<xsl:output method="text" /> |
<xsl:output method="text" /> |
||
<xsl:template match="/"> |
<xsl:template match="/"> |
||
Line 619: | Line 595: | ||
<xsl:copy-of select="//name" /> |
<xsl:copy-of select="//name" /> |
||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet> |
</xsl:stylesheet></lang> |
||
</nowiki></pre> |