XML/XPath: Difference between revisions
Added FreeBASIC
Thundergnat (talk | contribs) (Rename Perl 6 -> Raku, alphabetize, minor clean-up) |
(Added FreeBASIC) |
||
(13 intermediate revisions by 9 users not shown) | |||
Line 36:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program xpathXml64.s */
Line 254:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{output}}
<pre>
Line 284:
''AppleScript has no-built in support for XPath, but it could be used via a 'do shell script' command. Here's a solution using Apple System Events.
<
<section name=\"health\">
<item upc=\"123456789\" stock=\"12\">
Line 344:
return my getElementValuesByName(xmlData's contents, "price") -- Solution to part 3 of problem.
end tell</
<name>Invisibility Cream</name>
<price>14.50</price>
Line 352:
{"Invisibility Cream", "Levitation Salve", "Blork and Freen Instameal", "Grob winglets"}
{"14.50", "23.99", "4.95", "3.56"}</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program xpathXml.s */
Line 590:
bx lr @ return
</syntaxhighlight>
{{output}}
<pre>
Line 617:
=={{header|AutoHotkey}}==
With regular expressions
<
RegExMatch(inventory, "<item.*?</item>", item1)
Line 628:
While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1)
names .= name . "`n"
MsgBox % names</
{{libheader|AHK XPath}}
<
xpath_load(doc, "xmlfile.xml")
Line 644:
; Get an array of all the "name" elements
MsgBox % xpath(doc, "/inventory/section/item/name")</
=={{header|Bracmat}}==
<
( nestML$(get$("doc.xml",X,ML))
: ?
Line 712:
?
| out$!anArray {Not truly an array, but a list.}
);</
=={{header|C}}==
{{libheader|LibXML}}
Takes XML document and XPath expression as inputs and prints results, usage is printed if invoked incorrectly.
<syntaxhighlight lang="c">
#include <libxml/parser.h>
#include <libxml/xpath.h>
Line 773:
return 0;
}
</
testXML.xml contains the XML mentioned in the task description. Code must be compiled with the correct flags.
<pre>
Line 790:
=={{header|C sharp}}==
<
// Either read the xml from a string ...
Line 831:
// Convert the generic list to an array and output the count of items.
Console.WriteLine(NodesValues.ToArray().Length);</
=={{header|C++}}==
Line 838:
{{libheader|LibXML}}
<
#include <cstdlib>
#include <iostream>
Line 1,027:
}
}
</syntaxhighlight>
=={{header|Caché ObjectScript}}==
<
{
Line 1,099:
}
}</
{{out|Examples}}
<pre>
Line 1,110:
=={{header|CoffeeScript}}==
<div class='mw-collapsible mw-collapsed'>
<
doc = new DOMParser().parseFromString '
<inventory title="OmniCorp Store #45x10^3">
Line 1,139:
</inventory>
', 'text/xml'
</syntaxhighlight>
</div>
<nowiki>#</nowiki> "doc" is the XML as a Document object. Click expand to see parsing code ⇒
<
# Retrieve the first "item" element
doc.evaluate('//item', doc, {}, 7, {}).snapshotItem 0
Line 1,156:
names = for i in [0...names.snapshotLength] by 1
names.snapshotItem i
</syntaxhighlight>
=={{header|ColdFusion}}==
<
<inventory
...
Line 1,179:
<cfset names = xmlSearch(xml, "//name")>
<!--- visualize the results --->
<cfdump var="#variables#"></
=={{header|Common Lisp}}==
Line 1,186:
{{libheader|cxml-stp}}
<
(asdf:oos 'asdf:load-op system))
Line 1,200:
(node-array
(xpath:evaluate "/inventory/section/item/name" *doc*))</
=={{header|D}}==
It is important to note that the KXML library currently only supports XPath minimally.
{{libheader|KXML}}
<
char[]xmlinput =
"<inventory title=\"OmniCorp Store #45x10^3\">
Line 1,241:
}
auto namearray = root.parseXPath("inventory/section/item/name");
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,308:
for s in lItemNames do
Writeln('Item name = ' + s);
end.</
Output:
<syntaxhighlight lang="text">First item node:
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
Line 1,326:
Item name = Levitation Salve
Item name = Blork and Freen Instameal
Item name = Grob winglets</
=={{header|E}}==
Line 1,332:
{{libheader|E-XML}} (currently a very early work in progress/draft library; design comments welcome)
<
> def xpath__quasiParser := xml__quasiParser.xPathQuasiParser()
> null
Line 1,382:
# xml`<name>Blork and Freen Instameal</name>`,
# xml`<name>Grob winglets</name>`]
</syntaxhighlight>
=={{header|Erlang}}==
Line 1,388:
{{libheader|xmerl}}
<
-module(xml_xpath).
-include_lib("xmerl/include/xmerl.hrl").
Line 1,437:
[ Content#xmlText.value
|| #xmlElement{content = [Content|_]} <- xmerl_xpath:string("//name", Document)].
</syntaxhighlight>
Output:<pre>First item:
Line 1,454:
"Blork and Freen Instameal","Grob winglets"]
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="vbnet">Dim As String XML, item, price, nombre
Dim As Integer P1, P2
'' Read the XML file
Open "test3.xml" For Input As #1
XML = Input(Lof(1), #1)
Close #1
'' Find the first 'item' element
P1 = Instr(XML, "<item ")
P2 = Instr(XML, "</item>")
item = Mid(XML, P1, P2-P1+7)
Print "The first 'item' element is:"
Print item
'' Find all 'price' elements
Print "The 'prices' are:"
P1 = 1
Do
P1 = Instr(P1, XML, "<price>")
If P1 = 0 Then Exit Do
P2 = Instr(P1, XML, "</price>")
price = Mid(XML, P1+7, P2-P1-7)
Print price
P1 = P2 + 1
Loop
'' Find all 'nombre' elements
Print !"\nThe 'names' are:"
P1 = 1
Do
P1 = Instr(P1, XML, "<name>")
If P1 = 0 Then Exit Do
P2 = Instr(P1, XML, "</name>")
nombre = Mid(XML, P1+6, P2-P1-6)
Print nombre
P1 = P2 + 1
Loop
Sleep</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
open System.IO
open System.Xml.XPath
Line 1,499 ⟶ 1,541:
// array of all name elements
let names = seq { for name in nav.Select(@"//name") do yield name } |> Seq.toArray</
=={{header|Factor}}==
Line 1,506 ⟶ 1,548:
{{libheader|xml.traversal}}
<
! Get first item element
Line 1,591 ⟶ 1,633:
</section>
</inventory>""" string>xml "name" deep-tags-named
</syntaxhighlight>
=={{header|Gastona}}==
The example uses the command XMELON which parses a XML file of any schema and stores its
contents into db tables. This parser is described in the article [http://web3.codeproject.com/Articles/680642/XMeLon-Schema XMeLon-Schema]
<
<frames> oSal, XML Path sample, 300, 400
Line 1,674 ⟶ 1,716:
,, VAR+, tabnames, @<value>
DUMP, data,, tabnames
</syntaxhighlight>
{{out|Output}}
Line 1,704 ⟶ 1,746:
=={{header|Go}}==
Using the standard <code>encoding/xml</code> package:
<
import (
Line 1,783 ⟶ 1,825:
}
fmt.Printf("names: %q\n", names)
}</
{{out}}
<pre>
Line 1,806 ⟶ 1,848:
{{libheader|xmlpath}}
<
import (
Line 1,843 ⟶ 1,885:
fmt.Println("no names")
}
}</
{{out}}
<pre>
Line 1,853 ⟶ 1,895:
=={{header|Groovy}}==
<
def firstItem = inventory.section.item[0] //1. first item
inventory.section.item.price.each { println it } //2. print each price
def allNamesArray = inventory.section.item.name.collect {it} //3. collect item names into an array</
=={{header|Haskell}}==
<
import Control.Arrow
import Control.Monad
Line 1,883 ⟶ 1,925:
putStrLn "\n== Names ==\n"
print $ getsingleLineItems "name" xmlText</
Using the Haskell XML Toolkit (HXT):
<
import Text.XML.HXT.Arrow
{- For HXT version >= 9.0, use instead:
Line 1,902 ⟶ 1,944:
[(item, names)] <- runX (readDocument [] "xmlpath.xml" >>> process)
print item
print names</
=={{header|HicEst}}==
<
READ(ClipBoard) xml
Line 1,919 ⟶ 1,961:
EDIT(Text=xml, SPR='<>', R='<name>', W=1, WordEnd=$CR, APpendTo=output, DO=999)
WRITE(ClipBoard) TRIM(output) </
<
<name>Invisibility Cream</name>
<price>14.50</price>
Line 1,933 ⟶ 1,975:
Blork and Freen Instameal
Grob winglets
</syntaxhighlight>
=={{header|Java}}==
<
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
Line 1,995 ⟶ 2,037:
}
}
}</
=={{header|JavaScript}}==
{{works with|Firefox|2.0}}
<
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
Line 2,021 ⟶ 2,063:
namesArray.push( name );
}
alert( namesArray );</
Although some browsers support XPath, working with XML is much easier with E4X.
<
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', false);
Line 2,045 ⟶ 2,087:
names.push( name );
}
alert( names );</
=={{header|Julia}}==
Line 2,051 ⟶ 2,093:
vague about output format, so this is varied in the solution below. The first
test prints the raw XML node, and the second and third are further processed.
<
xdoc = raw"""<inventory title="OmniCorp Store #45x10^3">
Line 2,096 ⟶ 2,138:
namearray = LibExpat.find(etree, "//name")
println("Array of names of items:\n\t", map(s -> debracket(string(s)), namearray))
</
The first item's node XML entry is:
<item upc="123456789" stock="12">
Line 2,117 ⟶ 2,159:
=={{header|Kotlin}}==
<
import javax.xml.parsers.DocumentBuilderFactory
Line 2,179 ⟶ 2,221:
println("\nThe names of each item are as follows :")
println(" ${names.joinToString("\n ")}")
}</
{{out}}
Line 2,193 ⟶ 2,235:
Grob winglets
</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# Perform XPath queries on a XML Document
# # Variables:
#
typeset -T Xml_t=(
typeset -h 'UPC' upc
typeset -i -h 'num in stock' stock=0
typeset -h 'name' name
typeset -F2 -h 'price' price
typeset -h 'description' description
function init_item {
typeset key ; key="$1"
typeset val ; val="${2%\<\/${key}*}"
case ${key} in
upc) _.upc="${val//@(\D)/}"
;;
stock) _.stock="${val//@(\D)/}"
;;
name) _.name="${val%\<\/${key}*}"
;;
price) _.price="${val}"
;;
description) _.description=$(echo ${val})
;;
esac
}
function prt_item {
print "upc= ${_.upc}"
print "stock= ${_.stock}"
print "name= ${_.name}"
print "price= ${_.price}"
print "description= ${_.description}"
}
)
# # Functions:
#
######
# main #
######
integer i=0
typeset -a Item_t
buff=$(< xmldoc) # read xmldoc
item=${buff%%'</item>'*} ; buff=${.sh.match}
while [[ -n ${item} ]]; do
Xml_t Item_t[i]
item=${item#*'<item'} ; item=$(echo ${item})
for word in ${item}; do
if [[ ${word} == *=* ]]; then
Item_t[i].init_item ${word%\=*} ${word#*\=}
else
if [[ ${word} == \<* ]]; then # Beginning
key=${word%%\>*} ; key=${key#*\<}
val=${word#*\>}
fi
[[ ${word} != \<* && ${word} != *\> ]] && val+=" ${word} "
if [[ ${word} == *\> ]]; then # End
val+=" ${word%\<${key}\>*}"
Item_t[i].init_item "${key}" "${val}"
fi
fi
done
(( i++ ))
item=${buff#*'</item>'} ; item=${item%%'</item>'*} ; buff=${.sh.match}
done
print "First Item element:"
Item_t[0].prt_item
typeset -a names
printf "\nList of prices:\n"
for ((i=0; i<${#Item_t[*]}-1; i++)); do
print ${Item_t[i].price}
names[i]=${Item_t[i].name}
done
printf "\nArray of names:\n"
for (( i=0; i<${#names[*]}; i++)); do
print "names[$i] = ${names[i]}"
done</syntaxhighlight>
{{out}}<pre>
First Item element:
upc= 123456789
stock= 12
name= Invisibility Cream
price= 14.50
description= Makes you invisible
List of prices:
14.50
23.99
4.95
3.56
Array of names:
names[0] = Invisibility Cream
names[1] = Levitation Salve
names[2] = Blork and Freen Instameal
names[3] = Grob winglets</pre>
=={{header|Lasso}}==
Lasso has built in support for both XML handling and Xpaths
<
define xml_attrmap(in::xml_namedNodeMap_attr) => {
local(out = map)
Line 2,265 ⟶ 2,420:
'<br /><br />'
'<strong>Array with all names:</strong><br />'
#xml -> extract('//name') -> asstaticarray</
Output:
<pre>First item:
Line 2,282 ⟶ 2,437:
=={{header|LiveCode}}==
Copy the xml in this task into a text field called "FieldXML"
<
// task 1
Line 2,295 ⟶ 2,450:
filter namenodes without empty
split namenodes using cr
put namenodes is an array</
=={{header|Lua}}==
Requires LuaExpat
<
data = [[<inventory title="OmniCorp Store #45x10^3">
<section name="health">
Line 2,342 ⟶ 2,497:
print('Name: ', table.concat(names, ', '))
print('Price: ', table.concat(prices, ', '))</
Output:<pre>
<item upc="123456789" stock="12">
Line 2,353 ⟶ 2,508:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Cases[example, XMLElement["item", _ , _] , Infinity] // First
Cases[example, XMLElement["price", _, List[n_]] -> n, Infinity] // Column
Cases[example, XMLElement["name", _, List[n_]] -> n, Infinity] // Column</
{{out}}
<pre>XMLElement[item,{upc->123456789,stock->12},
{XMLElement[name,{},{Invisibility Cream}],XMLElement[price,{},{14.50}],XMLElement[description,{},{Makes you invisible}]}]
14.50
23.99
4.95
3.56
Invisibility Cream
Levitation Salve
Blork and Freen Instameal
Grob winglets</pre>
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java
import javax.xml.parsers.
import javax.xml.xpath.
import org.w3c.dom.
import org.w3c.dom.Node
import org.xml.sax.
Line 2,453 ⟶ 2,606:
return
</syntaxhighlight>
'''Output:'''
<pre>
Line 2,473 ⟶ 2,626:
=={{header|Nim}}==
{{libheader|libxml2}}
Nim standard library provides several modules to process XML, but none to process XPath requests. There is no third party library to do that either.
So we provide here a solution which uses the C "libxml2" library. Nim allows to interface with C with a great flexibility. Declaring the external functions is quite easy. The major part of the work consists to declare the data types. In "libxml2" there are a lot of structures and we have translated only what is needed to solve the task (or actually a bit more).
For the first request, we use <code>//section[1]/item[1]</code> instead of <code>//item[1]</code> (this is also what the Python version does). The latter request works but it returns the first element in each section which doesn’t seem to be what is expected.
<syntaxhighlight lang="nim">import sequtils, strutils
const LibXml = "libxml2.so"
type
XmlDocPtr = pointer
XmlXPathContextPtr = pointer
XmlElementKind = enum
xmlElementNode = 1
xmlAttributeNode = 2
xmlTextNode = 3
xmlCdataSectionNode = 4
xmlEntityRefNode = 5
xmlEntityNode = 6
xmlPiNode = 7
xmlCommentNode = 8
xmlDocumentNode = 9
xmlDocumentTypeNode = 10
xmlDocumentFragNode = 11
xmlNotationNode = 12
xmlHtmlDocumentNode = 13
xmlDtdNode = 14
xmlElementDecl = 15
xmlAttributeDecl = 16
xmlEntityDecl = 17
xmlNamespaceDecl = 18
xmlXincludeStart = 19
xmlXincludeEnd = 20
XmlNsKind = XmlElementKind
XmlNsPtr = ptr XmlNs
XmlNs = object
next: XmlNsPtr
kind: XmlNsKind
href: cstring
prefix: cstring
private: pointer
context: XmlDocPtr
XmlAttrPtr = pointer
XmlNodePtr = ptr XmlNode
XmlNode = object
private: pointer
kind: XmlElementKind
name: cstring
children: XmlNodePtr
last: XmlNodePtr
parent: XmlNodePtr
next: XmlNodePtr
prev: XmlNodePtr
doc: XmlDocPtr
ns: XmlNsPtr
content: cstring
properties: XmlAttrPtr
nsDef: XmlNsPtr
psvi: pointer
line: cushort
extra: cushort
XmlNodeSetPtr = ptr XmlNodeSet
XmlNodeSet = object
nodeNr: cint
nodeMax: cint
nodeTab: ptr UncheckedArray[XmlNodePtr]
XmlPathObjectKind = enum
xpathUndefined
xpathNodeset
xpathBoolean
xpathNumber
xpathString
xpathPoint
xpathRange
xpathLocationset
xpathUsers
xpathXsltTree
XmlXPathObjectPtr = ptr XmlXPathObject
XmlXPathObject = object
kind: XmlPathObjectKind
nodeSetVal: XmlNodeSetPtr
boolVal: cint
floatVal: cdouble
stringVal: cstring
user: pointer
index: cint
user2: pointer
index2: cint
XmlSaveCtxtPtr = pointer
XmlBufferPtr = pointer
# Declaration of needed "libxml2" procedures.
proc xmlParseFile(docName: cstring): XmlDocPtr
{.cdecl, dynlib: LibXml, importc: "xmlParseFile".}
proc xmlXPathNewContext(doc: XmlDocPtr): XmlXPathContextPtr
{.cdecl, dynlib: LibXml, importc: "xmlXPathNewContext".}
proc xmlXPathEvalExpression(str: cstring; ctxt: XmlXPathContextPtr): XmlXPathObjectPtr
{.cdecl, dynlib: LibXml, importc: "xmlXPathEvalExpression".}
proc xmlXPathFreeContext(ctxt: XmlXPathContextPtr)
{.cdecl, dynlib: LibXml, importc: "xmlXPathFreeContext".}
proc xmlXPathFreeObject(obj: XmlXPathObjectPtr)
{.cdecl, dynlib: LibXml, importc: "xmlXPathFreeObject".}
proc xmlSaveToBuffer(vuffer: XmlBufferPtr; encoding: cstring; options: cint): XmlSaveCtxtPtr
{.cdecl, dynlib: LibXml, importc: "xmlSaveToBuffer".}
proc xmlBufferCreate(): XmlBufferPtr
{.cdecl, dynlib: LibXml, importc: "xmlBufferCreate".}
proc xmlBufferFree(buf: XmlBufferPtr)
{.cdecl, dynlib: LibXml, importc: "xmlBufferCreate".}
proc xmlBufferContent(buf: XmlBufferPtr): cstring
{.cdecl, dynlib: LibXml, importc: "xmlBufferContent".}
proc xmlSaveTree(ctxt: XmlSaveCtxtPtr; cur: XmlNodePtr): clong
{.cdecl, dynlib: LibXml, importc: "xmlSaveTree".}
proc xmlSaveClose(ctxt: XmlSaveCtxtPtr)
{.cdecl, dynlib: LibXml, importc: "xmlSaveClose".}
proc `$`(node: XmlNodePtr): string =
## Return the representation of a node.
let buffer = xmlBufferCreate()
let saveContext = xmlSaveToBuffer(buffer, nil, 0)
discard saveContext.xmlSaveTree(node)
saveContext.xmlSaveClose()
result = $buffer.xmlBufferContent()
xmlBufferFree(buffer)
iterator nodes(xpath: string; context: XmlXPathContextPtr): XmlNodePtr =
## Yield the nodes which fit the XPath request.
let xpathObj = xmlXPathEvalExpression(xpath, context)
if xpathObj.isNil:
quit "Failed to evaluate XPath: " & xpath, QuitFailure
assert xpathObj.kind == xpathNodeset
let nodeSet = xpathObj.nodeSetVal
if not nodeSet.isNil:
for i in 0..<nodeSet.nodeNr:
yield nodeSet.nodeTab[i]
xmlXPathFreeObject(xpathObj)
# Load and parse XML file.
let doc = xmlParseFile("xpath_test.xml")
if doc.isNil:
quit "Unable to load and parse document", QuitFailure
# Create an XPath context.
let context = xmlXPathNewContext(doc)
if context.isNil:
quit "Failed to create XPath context", QuitFailure
var xpath = "//section[1]/item[1]"
echo "Request $#:".format(xpath)
for node in nodes(xpath, context):
echo node
echo()
xpath = "//price/text()"
echo "Request $#:".format(xpath)
for node in nodes(xpath, context):
echo node.content
echo()
xpath = "//name"
echo "Request $#:".format(xpath)
let names = toSeq(nodes(xpath, context)).mapIt(it.children.content)
echo names
xmlXPathFreeContext(context)</syntaxhighlight>
{{out}}
<pre>Request //section[1]/item[1]:
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
Request //price/text():
14.50
23.99
4.95
3.56
Request //name:
@["Invisibility Cream", "Levitation Salve", "Blork and Freen Instameal", "Grob winglets"]</pre>
=={{header|Objeck}}==
XPath is used to fetch element tags.
<
use XML;
Line 2,548 ⟶ 2,896:
}
}
</syntaxhighlight>
=={{header|Oz}}==
We implement a small subset of XPath for this task:
<
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Line 2,638 ⟶ 2,986:
#"</inventory>"
in
{Main Data}</
=={{header|Perl}}==
{{libheader|XML::XPath}}
<
my $x = XML::XPath->new('<inventory ... </inventory>');
Line 2,648 ⟶ 2,996:
[$x->findnodes('//item[1]')->get_nodelist]->[0];
print $x->findnodes_as_string('//price');
$x->findnodes('//name')->get_nodelist;</
=={{header|Phix}}==
Phix has no direct support for XPath, but achieving the requirements using the standard xml_parse() is not exactly difficult.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">xml</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">xml_txt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<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>
</section>
<section name="food">
<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>
</section>
</inventory>
"""</span><span style="color: #0000FF;">,</span>
<span style="color: #000080;font-style:italic;">-- or, of course, xml_txt = get_text("input.xml")</span>
<span style="color: #000000;">xml</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xml_parse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xml_txt</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sections</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xml_get_nodes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xml</span><span style="color: #0000FF;">[</span><span style="color: #000000;">XML_CONTENTS</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"section"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">item1</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
<span style="color: #000000;">prices</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
<span style="color: #000000;">names</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sections</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">items</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xml_get_nodes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sections</span><span style="color: #0000FF;">[</span><span style="color: #000000;">s</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"item"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">item1</span><span style="color: #0000FF;">={}</span> <span style="color: #008080;">then</span> <span style="color: #000000;">item1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">items</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">items</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">prices</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prices</span><span style="color: #0000FF;">,</span><span style="color: #000000;">xml_get_nodes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">items</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"price"</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">XML_CONTENTS</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">names</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">,</span><span style="color: #000000;">xml_get_nodes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">items</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"name"</span><span style="color: #0000FF;">)[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">XML_CONTENTS</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===item[1]===\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xml_new_doc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">item1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">xml_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tmp</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===prices===\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prices</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"===names===\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_Maxlen</span><span style="color: #0000FF;">,</span><span style="color: #000000;">90</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
===item[1]===
<?xml version="1.0" encoding="utf-8" ?>
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
===prices===
{`14.50`, `23.99`, `4.95`, `3.56`}
===names===
{`Invisibility Cream`, `Levitation Salve`, `Blork and Freen Instameal`, `Grob winglets`}
</pre>
=={{header|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>');
Line 2,680 ⟶ 3,100:
{
$result[] = $node;
}</
=={{header|PicoLisp}}==
<
(let Sections (body (in "file.xml" (xml)))
Line 2,694 ⟶ 3,114:
(for S Sections
(for L (body S)
(link (car (body L 'name))) ) ) ) )</
Output:
<pre>(item
Line 2,709 ⟶ 3,129:
=={{header|PowerShell}}==
Cast the <code>$document</code> string as <code>[xml]</code> and you have access to .NET methods affecting XML.
<syntaxhighlight lang="powershell">
$document = [xml]@'
<inventory title="OmniCorp Store #45x10^3">
Line 2,741 ⟶ 3,161:
$query = "/inventory/section/item"
$items = $document.SelectNodes($query)
</syntaxhighlight>
The first item:
<syntaxhighlight lang="powershell">
$items[0]
</syntaxhighlight>
{{Out}}
<pre>
Line 2,755 ⟶ 3,175:
</pre>
Get some useful information:
<syntaxhighlight lang="powershell">
$namesAndPrices = $items | Select-Object -Property name, price
$namesAndPrices
</syntaxhighlight>
{{Out}}
<pre>
Line 2,769 ⟶ 3,189:
</pre>
Here are the prices:
<syntaxhighlight lang="powershell">
$items.price
</syntaxhighlight>
{{Out}}
<pre>
Line 2,780 ⟶ 3,200:
</pre>
Here are the names:
<syntaxhighlight lang="powershell">
$items.name
</syntaxhighlight>
{{Out}}
<pre>
Line 2,792 ⟶ 3,212:
=={{header|Python}}==
<
from xml.dom import minidom
Line 2,809 ⟶ 3,229:
# 3rd Task: Get an array of all the "name" elements
namesArray = xmldoc.getElementsByTagName("name")</
In Python 2.5+ you can use ElementTree's limited XPath support
<
import xml.etree.ElementTree as ET
Line 2,829 ⟶ 3,249:
# list of names
names = doc.findall("section/item/name") # or ".//name"</
Or, you can install the <tt>lxml</tt> package and get full XPath support
<
from lxml import etree
Line 2,846 ⟶ 3,266:
print "{0:0.2f}".format(float(p.text)) # could raise exception on missing text or invalid float() conversion
names = doc.xpath("//name") # list of names</
=={{header|R}}==
{{libheader|XML (R)}}
<syntaxhighlight lang="r">
library("XML")
doc <- xmlInternalTreeParse("test3.xml")
# Retrieve the first "item" element
getNodeSet(doc, "//item")[[1]]
# Perform an action on each "price" element
sapply(getNodeSet(doc, "//price"), xmlValue)
# Get an array of all the "name" elements
sapply(getNodeSet(doc, "//name"), xmlValue)
</syntaxhighlight>
=={{header|Racket}}==
<
#lang at-exp racket
Line 2,910 ⟶ 3,334:
(se-path*/list '(item name) data)
;; => '("Invisibility Cream" "Levitation Salve" "Blork and Freen Instameal" "Grob winglets")
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my $XML = XML::XPath.new(xml => q:to/END/);
Line 2,951 ⟶ 3,375:
.contents.put for $XML.find('//price').List;
put "\nName elements:\n", $XML.find('//name')».contents.join: ', ';</
{{out}}
<pre>First item:
Line 2,966 ⟶ 3,390:
=={{header|Rascal}}==
<
import Prelude;
Line 2,988 ⟶ 3,412:
L += n;
return L;
}</
Example output:
<
<?xml version="1.0" encoding="UTF-8"?>
<item stock="12" upc="123456789">
Line 3,009 ⟶ 3,433:
rascal>get_names(|file:///Users/.../Desktop/xmlpath.xml|)
list[str]: ["Invisibility Cream","Levitation Salve","Blork and Freen Instameal","Grob winglets"]</
=={{header|REXX}}==
===hard coded parsing===
<
iFID='XPATH.XML' /*name of the input XML file (doc). */
$= /*string will contain the file's text. */
Line 3,047 ⟶ 3,471:
say names.k /*display a name from the NAMES list.*/
end /*k*/
/*stick a fork in it, we're all done. */</
'''output'''
<pre>
Line 3,064 ⟶ 3,488:
===generic parsing===
<
iFID='XPATH.XML' /*name of the input XML file (doc). */
$= /*string will contain the file's text. */
Line 3,095 ⟶ 3,519:
end /*#*/
#=#-1 /*adjust # of thing found.*/
return</
'''output''' is the same as the 1<sup>st</sup> version.
=={{header|Ruby}}==
{{libheader|REXML}}
<
require "rexml/document"
include REXML
Line 3,115 ⟶ 3,539:
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" )</
=={{header|Scala}}==
Line 3,122 ⟶ 3,546:
better show the results.
<
scala> val xml: scala.xml.Elem =
| <inventory title="OmniCorp Store #45x10^3">
Line 3,166 ⟶ 3,590:
scala> val names = (xml \\ "name").toArray
names: Array[scala.xml.Node] = Array(<name>Invisibility Cream</name>, <name>Levitation Salve</name>, <name>Blork and Freen Instameal</name>, <name>Grob winglets</name>)</
=={{header|SenseTalk}}==
<
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
Line 3,200 ⟶ 3,624:
put node "//item[1]" of XMLSource
put node "//price/text()" of XMLSource
put all nodes "//name" of XMLSource</
{{out}}
Line 3,215 ⟶ 3,639:
=={{header|Sidef}}==
{{trans|Perl}}
<
var x = %s'XML::XPath'.new(ARGF.slurp);
Line 3,221 ⟶ 3,645:
[x.findnodes('//item[1]')][0];
say [x.findnodes('//price')].map{x.getNodeText(_)};
[x.findnodes('//name')];</
{{out}}
Line 3,230 ⟶ 3,654:
=={{header|Tcl}}==
{{libheader|tDOM}}
<
package require tdom
set doc [dom parse $xml]
Line 3,243 ⟶ 3,667:
foreach node [$root selectNodes //price] {
puts [$node text]
}</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT,{}
MODE DATA
Line 3,309 ⟶ 3,733:
names=SPLIT(names)
TRACE *firstitem,names
</syntaxhighlight>
Output:
<pre style='height:30ex;overflow:scroll'>
Line 3,331 ⟶ 3,755:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Set objXMLDoc = CreateObject("msxml2.domdocument")
Line 3,361 ⟶ 3,785:
WScript.StdOut.Write list_name
WScript.StdOut.WriteBlankLines(2)
</syntaxhighlight>
{{out}}
<pre>
Line 3,377 ⟶ 3,801:
=={{header|Visual Basic .NET}}==
<
Console.WriteLine(first_item)
Line 3,384 ⟶ 3,808:
Next
Dim names = (From item In xml.XPathSelectElements("//name") Select item.Value).ToArray</
=={{header|Wren}}==
{{libheader|Wren-pattern}}
Wren does not have built-in support for XML/XPath and, to my knowledge, there is no third party module which adds such support either. We therefore have to fall back on string pattern matching to perform the required queries.
<syntaxhighlight lang="wren">import "./pattern" for Pattern
var doc = """
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<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>
</section>
<section name="food">
<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>
</section>
</inventory>
"""
var p1 = Pattern.new("<item ")
var match1 = p1.find(doc)
var p2 = Pattern.new("<//item>")
var match2 = p2.find(doc)
System.print("The first 'item' element is:")
System.print(" " + doc[match1.index..match2.index + 6])
var p3 = Pattern.new("<price>[+1^<]<//price>")
var matches = p3.findAll(doc)
System.print("\nThe 'prices' are:")
for (m in matches) System.print(m.captures[0].text)
var p4 = Pattern.new("<name>[+1^<]<//name>")
var matches2 = p4.findAll(doc)
var names = matches2.map { |m| m.captures[0].text }.toList
System.print("\nThe 'names' are:")
System.print(names.join("\n"))</syntaxhighlight>
{{out}}
<pre>
The first 'item' element is:
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
The 'prices' are:
14.50
23.99
4.95
3.56
The 'names' are:
Invisibility Cream
Levitation Salve
Blork and Freen Instameal
Grob winglets
</pre>
<br>
{{libheader|Wren-xsequence}}
Since the first version was written, the above XML parser has appeared. Consequently, the solution can now be rewritten as follows, the output being the same as before.
Note that this library doesn't support XPath as such though for this particular task simple 'for' statements suffice.
<syntaxhighlight lang="wren">import "./xsequence" for XDocument
var xml = """
<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<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>
</section>
<section name="food">
<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>
</section>
</inventory>
"""
var doc = XDocument.parse(xml)
System.print("The first 'item' element is:")
System.print(doc.root.element("section").element("item"))
var prices = []
var names = []
for (el in doc.root.elements) {
for (el2 in el.elements) {
prices.add(el2.element("price").value)
names.add(el2.element("name").value)
}
}
System.print("\nThe 'prices' are:\n%(prices.join("\n"))")
System.print("\nThe 'names' are:\n%(names.join("\n"))")</syntaxhighlight>
=={{header|XPL0}}==
To run: xml <xml.xml
<syntaxhighlight lang "XPL0">include xpllib; \for StrFind
char XML(1000000), P, P1, P2, Addr;
int I, Ch;
[I:= 0;
loop [Ch:= ChIn(1);
XML(I):= Ch;
if Ch = $1A \EOF\ then quit;
I:= I+1;
];
XML(I):= 0;
P1:= StrFind(XML, "<item ");
P2:= StrFind(XML, "</item>");
Text(0, "The first 'item' element is:^m^j");
for P:= P1 to P2+6 do ChOut(0, P(0));
CrLf(0);
Text(0, "^m^jThe 'prices' are:^m^j");
Addr:= XML;
loop [P1:= StrFind(Addr, "<price>");
if P1 = 0 then quit;
P2:= StrFind(Addr, "</price>");
if P2 = 0 then quit;
for P:= P1+7 to P2-1 do ChOut(0, P(0));
CrLf(0);
Addr:= P2+1;
];
Text(0, "^m^jThe 'names' are:^m^j");
Addr:= XML;
loop [P1:= StrFind(Addr, "<name>");
if P1 = 0 then quit;
P2:= StrFind(Addr, "</name>");
if P2 = 0 then quit;
for P:= P1+6 to P2-1 do ChOut(0, P(0));
CrLf(0);
Addr:= P2+1;
];
]</syntaxhighlight>
{{out}}
<pre>
The first 'item' element is:
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
The 'prices' are:
14.50
23.99
4.95
3.56
The 'names' are:
Invisibility Cream
Levitation Salve
Blork and Freen Instameal
Grob winglets
</pre>
=={{header|XProc}}==
<
name="one-two-three"
version="1.0">
Line 3,416 ⟶ 4,027:
</p:input>
</p:insert>
</p:pipeline></
=={{header|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 3,437 ⟶ 4,048:
<prices>{$price}</prices>
<names>{$names}</names>
</result></
Performing this XQuery on the given input document results in
<
<result>
<firstItem>
Line 3,456 ⟶ 4,067:
<name>Grob winglets</name>
</names>
</result></
=={{header|XSLT}}==
<
<xsl:output method="text" />
<xsl:template match="/">
Line 3,482 ⟶ 4,093:
<xsl:copy-of select="//name" />
</xsl:template>
</xsl:stylesheet></
{{omit from|Batch File|No way of XML parsing or processing.}}
|