Jump to content

XML/XPath: Difference between revisions

m
Fixed lang tags.
(added Haskell (without using specialized modules))
m (Fixed lang tags.)
Line 35:
=={{header|AutoHotkey}}==
With regular expressions
<lang AutoHotkey>FileRead, inventory, xmlfile.xml
FileRead, inventory, xmlfile.xml
 
RegExMatch(inventory, "<item.*?</item>", item1)
Line 47 ⟶ 46:
While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1)
names .= name . "`n"
MsgBox % names</lang>
</lang>
{{libheader|AHK XPath}}
<lang AutoHotkey>#Include xpath.ahk
#Include xpath.ahk
 
xpath_load(doc, "xmlfile.xml")
Line 65 ⟶ 62:
 
; Get an array of all the "name" elements
MsgBox % xpath(doc, "/inventory/section/item/name")</lang>
</lang>
 
=={{header|C sharp|C#}}==
<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++}}==
<lang C++cpp>#include <vector>
#include <string>
#include <iostream>
Line 174 ⟶ 170:
std::copy( names.begin( ) , names.end( ) , std::ostream_iterator<std::string>( std::cout , "\n" )) ;
return 0 ;
}</lang>
}
</lang>
 
=={{header|ColdFusion}}==
<lang cfm><cfsavecontent variable="xmlString">
<inventory
...
</inventory>
</cfsavecontent>
<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#"></lang>
 
=={{header|D}}==
It is important to note that the KXML library currently only supports XPath minimally.
{{libheader|KXML}}
<lang d>import kxml.xml;
import kxml.xml;
char[]xmlinput =
"<inventory title=\"OmniCorp Store #45x10^3\">
Line 240 ⟶ 234:
}
auto namearray = root.parseXPath("inventory/section/item/name");
}</lang>
}
 
</lang>
 
=={{header|Groovy}}==
Line 279 ⟶ 271:
=={{header|JavaScript}}==
{{works with|Firefox|2.0}}
<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.
 
<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}}==
{{libheader|XML::XPath}}
<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}}==
<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)
//Load from file instead with $doc = DOMDocument::loadXMLload('<inventory title="OmniCorp Store #45x10^3">...</inventory>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');
*/
$nodelistresult = $xpathnodelist->queryitem('//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}}==
<lang python># Python has basic xml parsing built in
# Python has basic xml parsing built in
 
from xml.dom import minidom
Line 390 ⟶ 379:
 
# 3rd Task: Get an array of all the "name" elements
namesArray = xmldoc.getElementsByTagName("name")</lang>
</lang>
 
=={{header|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")
doc <- xmlInternalTreeParse("test3.xml")
Line 405 ⟶ 392:
for(i in 1:length(prices)) print(prices[i])
# 3rd Task: Get an array of all the "name" elements
(namesArray <- sapply(getNodeSet(doc, "//name"), xmlValue))</lang>
 
</lang>
 
=={{header|Ruby}}==
{{libheader|REXML}}
<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}}==
Line 436 ⟶ 421:
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">
| <item upc="123456789" stock="12">
Line 516 ⟶ 500:
 
scala> val values = xml \\ "name" map (_ text) toArray
values: Array[String] = Array(Invisibility Cream, Levitation Salve, Blork and Freen Instameal, Grob winglets)</lang>
</lang>
 
=={{header|Tcl}}==
Line 538 ⟶ 521:
=={{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}}==
<lang xquery>(:
 
(:
1. Retrieve the first "item" element
Notice the braces around //item. This evaluates first all item elements and then retrieving the first one.
Line 569 ⟶ 550:
<prices>{$price}</prices>
<names>{$names}</names>
</result></lang>
</lang>
 
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>
<firstItem>
Line 590 ⟶ 569:
<name>Grob winglets</name>
</names>
</result></lang>
 
</lang>
 
=={{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:template match="/">
Line 619 ⟶ 595:
<xsl:copy-of select="//name" />
</xsl:template>
</xsl:stylesheet></lang>
</nowiki></pre>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.