XML/Input: Difference between revisions

22,705 bytes added ,  3 months ago
m
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(19 intermediate revisions by 11 users not shown)
Line 3:
Given the following XML fragment, extract the list of ''student names'' using whatever means desired. If the only viable method is to use XPath, refer the reader to the task [[XML and XPath]].
 
<langsyntaxhighlight lang="xml"><Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
Line 11:
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students></langsyntaxhighlight>
 
Expected Output
Line 22:
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
\ Load the XML text into the var 'x':
Line 46:
\ Iterate over the XML document in the var 'x'
x @ ' .xml xml:each bye
</syntaxhighlight>
</lang>
{{out}}
April<br>
Line 56:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputXml64.s */
Line 275:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 287:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package
{
import flash.display.Sprite;
Line 308:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
Line 316:
 
extract_students.adb:
<langsyntaxhighlight Adalang="ada">with Sax.Readers;
with Input_Sources.Strings;
with Unicode.CES.Utf8;
Line 338:
My_Reader.Parse (Reader, Input);
Input_Sources.Strings.Close (Input);
end Extract_Students;</langsyntaxhighlight>
 
my_reader.ads:
<langsyntaxhighlight Adalang="ada">with Sax.Attributes;
with Sax.Readers;
with Unicode.CES;
Line 352:
Qname : Unicode.CES.Byte_Sequence := "";
Atts : Sax.Attributes.Attributes'Class);
end My_Reader;</langsyntaxhighlight>
 
my_reader.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
package body My_Reader is
procedure Start_Element
Line 368:
end if;
end Start_Element;
end My_Reader;</langsyntaxhighlight>
 
Output:
Line 378:
 
===Alternative using a DOM document===
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Sax.Readers;
with Input_Sources.Strings;
Line 418:
end loop;
DOM.Readers.Free (Reader);
end Extract_Students;</langsyntaxhighlight>
 
output is the same.
Line 428:
main.adb:
 
<langsyntaxhighlight Adalang="ada">with League.Application;
with XML.SAX.Input_Sources.Streams.Files;
with XML.SAX.Simple_Readers;
Line 443:
Reader.Set_Content_Handler (Handler'Unchecked_Access);
Reader.Parse (Input'Unchecked_Access);
end Main;</langsyntaxhighlight>
 
handlers.ads:
 
<langsyntaxhighlight Adalang="ada">with League.Strings;
with XML.SAX.Attributes;
with XML.SAX.Content_Handlers;
Line 467:
(Self : Handler) return League.Strings.Universal_String;
 
end Handlers;</langsyntaxhighlight>
 
handlers.adb:
 
<langsyntaxhighlight Adalang="ada">with Ada.Wide_Wide_Text_IO;
 
package body Handlers is
Line 509:
end Start_Element;
 
end Handlers;</langsyntaxhighlight>
 
=={{header|Aikido}}==
Put the XML in the file called t.xml
<langsyntaxhighlight lang="aikido">
import xml
 
Line 529:
}
 
</syntaxhighlight>
</lang>
The output is (Aikido doesn't support unicode rendering):
April
Line 539:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program inputXml.s */
Line 821:
pop {r1-r4}
bx lr
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 831:
Normal end of program.
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">data: {
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>
}
 
students: read.xml data
print join.with:"\n" map students 'student -> student\Name</syntaxhighlight>
 
{{out}}
 
<pre>April
Bob
Chad
Dave
Émily</pre>
 
=={{header|AutoHotkey}}==
simply using regular expressions
<langsyntaxhighlight AutoHotkeylang="autohotkey">students =
(
<Students>
Line 853 ⟶ 878:
names .= name1 . "`n"
 
msgbox % names</langsyntaxhighlight>
 
=={{header|AWK}}==
The following code extracts the value of the property "Name" from every Student tag. It does not handle the <tt>&amp;#CODE;</tt>; this can be left to others: a way to cope with it fastly, is to output a very simple HTML structure, so that the interpretation is left to an HTML reader/browser.
 
<langsyntaxhighlight lang="awk">function parse_buf()
{
if ( match(buffer, /<Student[ \t]+[^>]*Name[ \t]*=[ \t]*"([^"]*)"/, mt) != 0 ) {
Line 913 ⟶ 938:
print k
}
}</langsyntaxhighlight>
Using [http://awk.info/?getxml getXML.awk] written by Jan Weber, one could do this:
 
{{works with|gawk}} or {{works with|nawk}}
<langsyntaxhighlight lang="awk">awk -f getXML.awk sample.xml | awk '
$1 == "TAG" {tag = $2}
tag == "Student" && /Name=/ {print substr($0, index($0, "=") + 1)}
'</langsyntaxhighlight>
Using [http://home.vrweb.de/~juergen.kahrs/gawk/XML/xmlgawk.html#Steve-Coile_0027s-xmlparse_002eawk-script xmlparser.awk] by Steve Coile, one can do this:
 
{{works with|gawk}}
<langsyntaxhighlight lang="awk">gawk -f xmlparser.awk sample.xml | awk '
$1 == "begin" {tag = $2}
$1 == "attrib" {attrib = $2}
$1 == "value" && tag == "STUDENT" && attrib == "name" {print $2}
'</langsyntaxhighlight>
 
Both of these produce this output
Line 950 ⟶ 975:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"XMLLIB"
xmlfile$ = "C:\students.xml"
PROC_initXML(xmlobj{}, xmlfile$)
Line 969 ⟶ 994:
UNTIL FN_getLevel(xmlobj{}) < level%
PROC_exitXML(xmlobj{})</langsyntaxhighlight>
Output:
<pre>
Line 983 ⟶ 1,008:
The read datastructure is a flat list of tags and text fragments. For proper nesting of elements extra code would have to be written, but in this simple task that is not necessary. On the downside, the pattern must both handle empty tags (the <code>(? (Name.?name) ?,</code> pattern) and open tags (the <code>? (Name.?name) ?</code> pattern).
Reading input from a file:
<langsyntaxhighlight lang="bracmat">( :?names
& ( get$("students.xml",X,ML)
: ?
Line 996 ⟶ 1,021:
| !names
)
)</langsyntaxhighlight>
 
Alternative solution, reading input from memory:
<langsyntaxhighlight lang="bracmat">( :?names
& ( get
$ ( "<Students>
Line 1,025 ⟶ 1,050:
| !names
)
)</langsyntaxhighlight>
Output:
<pre>April Bob Chad Dave Émily</pre>
Line 1,031 ⟶ 1,056:
=={{header|C}}==
 
==={{libheader|LibXML}}===
{{uses from|Library|libxml|component1=xmlDoc|component2=xmlNode|component3=xmlReadMemory|component4=xmlDocGetRootElement|component5=xmlFreeDoc|component6=xmlCleanupParser|component7=xmlNode|component8=XML_ELEMENT_NODE|component9=xmlAttr|component10=xmlHasProp}}
{{uses from|Library|C Runtime|component1=printf}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,081 ⟶ 1,106:
xmlCleanupParser();
return 0;
}</langsyntaxhighlight>
 
==={{libheader|Gadget}}===
<p>Gadget is a library for strings handler, not XML handler. But...</p>
<syntaxhighlight lang="c">
#include <gadget/gadget.h>
 
LIB_GADGET_START
 
Main
Assert( Arg_count == 2, end_input );
Get_arg_str( xml_file, 1 );
Assert( Exist_file(xml_file), file_not_exist );
 
char* xml = Load_string(xml_file);
ST_GETTAG field = Unparser( &xml, "Students");
Assert ( field.content, fail_content );
 
while ( Occurs ("Student",field.content ) )
{
ST_GETTAG sub_field = Unparser( &field.content, "Student");
 
if(sub_field.attrib)
{
int i=0;
Iterator up i [ 0: 1: sub_field.len ]
{
if ( strcmp(sub_field.name[i], "Name" )==0 )
{
Get_fn_let( sub_field.attrib[i], Str_tran( sub_field.attrib[i], "&#x00C9;","É" ) );
/* OK... I must write the function that change this diabolic characters :D */
Print "%s\n",sub_field.attrib[i];
break;
}
}
}
Free tag sub_field;
}
Free tag field;
/* Exceptions areas */
Exception( fail_content ){
Msg_red("Not content for \"Students\" field\n");
}
Free secure xml;
Exception( file_not_exist ){
Msg_redf("File \"%s\" not found\n", xml_file);
}
Free secure xml_file;
Exception( end_input ){
Msg_yellow("Use:\n RC_xml <xml_file.xml>");
}
End
</syntaxhighlight>
{{out}}
<pre>
$ ./tests/RC_xml xml_data.xml
April
Bob
Chad
Dave
Émily
 
$ ./tests/RC_xml somefile.xml
File "somefile.xml" not found
 
</pre>
<p>File: xml_data.xml:</p>
<syntaxhighlight lang="xml"><Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students></syntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
class Program
{
Line 1,100 ⟶ 1,207:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Line 1,107 ⟶ 1,214:
{{uses from|Library|Qt|component1=QDomDocument|component2=QObject|component3=QDomElement}}
 
<langsyntaxhighlight lang="cpp">/*
Using the Qt library's XML parser.
*/
Line 1,136 ⟶ 1,243:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Caché ObjectScript}}==
 
<langsyntaxhighlight lang="cos">Class XML.Students [ Abstract ]
{
 
Line 1,175 ⟶ 1,282:
}
 
}</langsyntaxhighlight>
{{out|Examples}}
<pre>
Line 1,190 ⟶ 1,297:
{{uses from|Library|clojure.xml|component1=parse}}
This version uses the standard Clojure function ''xml-seq'
<langsyntaxhighlight lang="lisp">
(import '(java.io ByteArrayInputStream))
(use 'clojure.xml) ; defines 'parse
Line 1,205 ⟶ 1,312:
 
(def students (parse (-> xml-text .getBytes ByteArrayInputStream.)))
</syntaxhighlight>
</lang>
 
The parse produces a data structure where each element is represented as a map with '':tag'', '':attrs'', and '':content'' keys.
Line 1,211 ⟶ 1,318:
''xml-seq'' produces a sequence of such nodes by walking the resulting tree.
 
<langsyntaxhighlight lang="lisp">
(doseq [{:keys [tag attrs]} (xml-seq students)]
(if (= :Student tag)
(println (:Name attrs))))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 1,221 ⟶ 1,328:
{{libheader|Closure XML}}
 
<langsyntaxhighlight lang="lisp">(defparameter *xml-blob*
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
Line 1,237 ⟶ 1,344:
(dom:do-node-list (child (dom:child-nodes students) (nreverse student-names))
(when (dom:element-p child)
(push (dom:get-attribute child "Name") student-names))))</langsyntaxhighlight>
 
produces<langsyntaxhighlight lang="lisp">("April" "Bob" "Chad" "Dave" "Émily")</langsyntaxhighlight>
 
=={{header|D}}==
{{libheader|KXML}}
<langsyntaxhighlight lang="d">import kxml.xml;
char[]xmlinput =
"<Students>
Line 1,266 ⟶ 1,373:
break;
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
//You need to use these units
uses
Line 1,316 ⟶ 1,423:
Showmessage(GetStudents(XMLInput));
end;
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( xml_input ).
 
Line 1,342 ⟶ 1,449:
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />
</Students>".
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,354 ⟶ 1,461:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System.IO
open System.Xml
open System.Xml.Linq
Line 1,379 ⟶ 1,486:
let names = students.Attributes <| xn "Name"
Seq.iter ((fun (a : XAttribute) -> a.Value) >> printfn "%s") names
0</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: io multiline sequences xml xml.data xml.traversal ;
 
: print-student-names ( string -- )
Line 1,395 ⟶ 1,502:
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>]] print-student-names</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
using xml
 
Line 1,417 ⟶ 1,524:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 1,423 ⟶ 1,530:
{{libheader|Forth Foundation Library}}
 
<langsyntaxhighlight lang="forth">include ffl/est.fs
include ffl/str.fs
include ffl/xis.fs
Line 1,470 ⟶ 1,577:
;
 
xmlparse</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,478 ⟶ 1,585:
Uses [https://github.com/DLR-SC/tixi tixi library] (+ LibXML, curl as dependencies)
 
<langsyntaxhighlight lang="fortran">
program tixi_rosetta
use tixi
Line 1,512 ⟶ 1,619:
 
end program tixi_rosetta
</syntaxhighlight>
</lang>
 
Compile
Line 1,532 ⟶ 1,639:
Uses [https://github.com/andreww/fox FoX]
 
<langsyntaxhighlight lang="fortran">
program fox_rosetta
use FoX_dom
Line 1,562 ⟶ 1,669:
call destroy(doc)
end program fox_rosetta
</syntaxhighlight>
</lang>
 
Output
Line 1,572 ⟶ 1,679:
Dave
&mily
</pre>
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<syntaxhighlight lang="vb">Data 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238
Data 248, 241, 253, 252, 239, 230, 244, 250, 247, 251, 167, 175, 172, 171, 243, 168
Data 183, 181, 182, 199, 142, 143, 146, 128, 212, 144, 210, 211, 222, 214, 215, 216
Data 209, 165, 227, 224, 226, 229, 153, 158, 157, 235, 233, 234, 154, 237, 232, 225
Data 133, 160, 131, 198, 132, 134, 145, 135, 138, 130, 136, 137, 141, 161, 140, 139
Data 208, 164, 149, 162, 147, 228, 148, 246, 155, 151, 163, 150, 129, 236, 231, 152
 
Dim Shared As Integer numCodes, initCode
initCode = 160
numCodes = 255 - initCode + 1
 
Dim Shared As Integer codes(numCodes)
For i As Integer = 0 To numCodes - 1 : Read codes(i)
Next i
 
Function codeConversion(charcode As Integer, tocode As Integer = False) As Integer
If tocode Then
For i As Integer = 0 To numCodes - 1
If codes(i) = charcode Then Return i + initCode
Next i
Else
Return codes(charcode - initCode)
End If
End Function
 
Function convASCII(nombre As String, mark As String) As String
Dim As Integer p, c, lm = Len(mark)
Do
p = Instr(p, nombre, mark)
If p = 0 Then Exit Do
c = Valint(Mid(nombre, p + lm, 4))
c = codeConversion(c)
nombre = Left(nombre, p-1) + Chr(c) + Right(nombre, Len(nombre) - (p + lm + 4))
p += 1
Loop
Return nombre
End Function
 
Dim As String strXml = "<Students>"
strXml += " <Student Name=\'April\' Gender=\'F\' DateOfBirth=\'1989-01-02\' />"
strXml += " <Student Name=\'Bob\' Gender=\'M\' DateOfBirth=\'1990-03-04\' />"
strXml += " <Student Name=\'Chad\' Gender=\'M\' DateOfBirth=\'1991-05-06\' />"
strXml += " <Student Name=\'Dave\' Gender=\'M\' DateOfBirth=\'1992-07-08\'>"
strXml += " <Pet Type=\'dog\' Name=\'Rover\' />"
strXml += " </Student>"
strXml += " <Student DateOfBirth=\'1993-09-10\' Gender=\'F\' Name=\'&#x00C9;mily\' />"
strXml += "</Students>"
 
Dim As String tag1 = "<Student"
Dim As String tag2 = "Name=\'", nombre
Dim As Integer ltag = Len(tag2), p = 1, p2
 
Do
p = Instr(p, strXml, tag1)
If p = 0 Then Exit Do
p = Instr(p, strXml, tag2)
p += ltag
p2 = Instr(p, strXml, "\'")
nombre = convASCII(Mid(strXml, p, p2 - p), "&#x")
Print nombre
Loop
 
Sleep</syntaxhighlight>
{{out}}
<pre>April
Bob
Chad
Dave
&#x00C9;mily</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
include "NSLog.incl"
include "Tlbx XML.incl"
 
#define STUDENTS_KEY @"Students"
#define STUDENT_KEY @"Student"
#define NAME_KEY @"Name"
 
void local fn MyParserDelegateCallback( ev as long, parser as XMLParserRef, userData as ptr )
static BOOL studentsFlag = NO
CFDictionaryRef attributes
CFStringRef name
select ( ev )
case _xmlParserDidStartElement
select ( fn XMLParserDelegateElementName(parser) )
case STUDENTS_KEY
studentsFlag = YES
case STUDENT_KEY
if ( studentsFlag )
attributes = fn XMLParserDelegateAttributes(parser)
name = fn DictionaryObjectForKey( attributes, NAME_KEY )
if ( name ) then NSLog(@"%@",name)
end if
end select
end select
end fn
 
void local fn ParseXMLFile
CFStringRef xmlString = @"<Students>\n"
xmlString = fn StringByAppendingFormat( xmlString, @"%@\n",@"<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"<Pet Type=\"dog\" Name=\"Rover\" />\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"</Student>\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n" )
xmlString = fn StringByAppendingFormat( xmlString, @"</Students>" )
CFDataRef xmlData = fn StringData( xmlString, NSUTF8StringEncoding )
XMLParserRef parser = fn XMLParserWithData( xmlData )
XMLParserSetDelegateCallback( parser, @fn MyParserDelegateCallback, NULL )
fn XMLParserParse( parser )
end fn
 
fn ParseXMLFile
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
April
Bob
Chad
Dave
Émily
</pre>
 
=={{header|Go}}==
Go's <tt>xml.Unmarshal</tt> uses reflection to fill in data-structures recursively.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,625 ⟶ 1,867:
fmt.Println(s.Name)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,636 ⟶ 1,878:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def input = """<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
Line 1,647 ⟶ 1,889:
 
def students = new XmlParser().parseText(input)
students.each { println it.'@Name' }</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Maybe
import Text.XML.Light
 
Line 1,664 ⟶ 1,906:
xmlRead elm name = mapM_ putStrLn
. concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm))
. onlyElems. parseXML</langsyntaxhighlight>
Show names:
<langsyntaxhighlight lang="haskell">*Main> xmlRead "Student" "Name" students
April
Bob
Chad
Dave
Émily</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">CHARACTER in*1000, out*100
 
READ(ClipBoard) in
EDIT(Text=in, SPR='"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO)</langsyntaxhighlight>
<pre>out is returned as:
April Bob Chad Dave &#x00C9;mily
Line 1,685 ⟶ 1,927:
J's system includes several XML processing libraries. This task is probably best addressed using XPath (this is the type of problem XPath was designed to solve), but the task description implicitly discourages that method. So we can use the SAX library instead:
 
<langsyntaxhighlight lang="j">load'xml/sax'
saxclass 'Students'
Line 1,691 ⟶ 1,933:
cocurrent'base'
process_Students_ XML</langsyntaxhighlight>
April
Bob
Line 1,699 ⟶ 1,941:
 
and the definition of the variable <code>XML</code>:
<langsyntaxhighlight lang="j">XML=: noun define
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 1,709 ⟶ 1,951:
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>
)</langsyntaxhighlight>
 
=={{header|Java}}==
{{uses from|Library|java.io|component1=IOException|component2=StringReader}}
{{uses from|Library|org.xml.sax|component1=Attributes|component2=InputSource|component3=SAXException|component4=XMLReader|component5=helpers.DefaultHandler|component6=helpers.XMLReaderFactory}}
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.io.StringReader;
import org.xml.sax.Attributes;
Line 1,764 ⟶ 2,006:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,770 ⟶ 2,012:
=== Browser version ===
This version tested against Chrome 37, Firefox 32, and IE 11:
<syntaxhighlight lang="javascript">
<lang JavaScript>
var xmlstr = '<Students>' +
'<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
Line 1,797 ⟶ 2,039:
console.log(students[e].attributes.Name.value);
}
</syntaxhighlight>
</lang>
{{works with|Mozilla Firefox|32}}
 
=== Node.js version ===
<syntaxhighlight lang="javascript">
<lang JavaScript>
var parseString = require('xml2js').parseString;
var xmlstr = '<Students>' +
Line 1,820 ⟶ 2,062:
}
});
</syntaxhighlight>
</lang>
 
=== E4X version ===
Alternatively, use the E4X featureset (currently only in Firefox):
<syntaxhighlight lang="javascript">
<lang JavaScript>
var xmlstr = '<Students>' +
'<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
Line 1,845 ⟶ 2,087:
 
alert(output);
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Neither the C nor the Go implementations of jq natively support XML,
so in this entry we present three solutions:
 
* the first uses `xq`, a jq "wrapper";
* the second uses a third-party XML-to-JSON translator, `knead`;
* the third is a "pure jq" solution based on a Parsing Expression Grammar for XML.
 
===xq===
xq is part of the python-yq package [https://github.com/kislyuk/yq].
<syntaxhighlight lang=jq>
xq -r '.Students.Student[]."@Name"' students.xml
</syntaxhighlight>
{{output}}
<pre>
April
Bob
Chad
Dave
Émily
</pre>
 
===knead | jq===
`knead` is part of the `dataknead` package at https://hay.github.io/dataknead/
<pre>
knead students.xml | jq -r '.Students.Student[]["@Name"]'
</pre>
{{Output}}
As above.
 
===PEG-based Parsing===
In this section, a PEG-based XML parser is presented. Its main goal is
to translate valid XML documents into valid JSON losslessly, rather
than to check for validity.
 
In particular, the relative ordering of embedded tags and "text"
fragments is preserved, as is "white space" when significant in
accordance with the XML specification.
 
Being PEG-based, however, the parser should be quite easy to adapt for other purposes.
 
A jq filter, `jsonify`, is also provided for converting hex character codes
of the form `&#x....;' to the corresponding character, e.g. "&#x00C9;mily" -> "Émily".
It also removes strings of the form '^\n *$' in the "text" portions of the XML document.
 
Some other noteworthy points:
 
* since "duplicate attribute names within a tag are not permitted with XML", we can group the attributes within a tag as a JSON object, as jq respects key ordering.
 
* since XML tags cannot begin with `@`, the "PROLOG" is rendered as a JSON object with key "@PROLOG" and likewise for "COMMENT", "DTD" and "CDATA".
 
* consecutive attribute-value pairs are grouped together under the key named "@attributes".
 
The grammar is primarily adapted from:
* (1) https://peerj.com/preprints/1503/
* (2) https://cs.lmu.edu/~ray/notes/xmlgrammar/
====PEG Infrastructure====
The jq module at [[:Category:Jq/peg.jq]] can be included by copying it to a file,
and adding an `include` statement to top of the main program, e.g. as follows:
<syntaxhighlight lang=jq>
include "peg" {search: "."};
</syntaxhighlight>
 
====XML Grammar====
<syntaxhighlight lang=jq>
def XML:
def String : ((consume("\"") | parse("[^\"]*") | consume("\"")) //
(consume("'") | parse("[^']*") | consume("'")));
 
def CDataSec : box("@CDATA"; q("<![CDATA[") | string_except("]]>") | q("]]>") ) | ws;
def PROLOG : box("@PROLOG"; q("<?xml") | string_except("\\?>") | q("?>"));
def DTD : box("@DTD"; q("<!") | parse("[^>]") | q(">"));
# The XML spec specifically disallows double-hyphen within comments
def COMMENT : box("@COMMENT"; q("<!--") | string_except("--") | q("-->"));
 
def CharData : parse("[^<]+"); # only `<` is disallowed
 
# This is more permissive than required:
def Name : parse("[A-Za-z:_][^/=<>\n\r\t ]*");
 
def Attribute : keyvalue(Name | ws | q("=") | ws | String | ws);
def Attributes: box( plus(Attribute) ) | .result[-1] |= {"@attributes": add} ;
 
# <foo> must be matched with </foo>
def Element :
def Content : star(Element // CDataSec // CharData // COMMENT);
objectify( q("<")
| Name
| .result[-1] as $name
| ws
| (Attributes // ws)
| ( (q("/>")
// (q(">") | Content | q("</") | q($name) | ws | q(">")))
| ws) ) ;
 
{remainder: . }
| ws
| optional(PROLOG) | ws
| optional(DTD) | ws
| star(COMMENT | ws)
| Element | ws # for HTML, one would use star(Element) here
| star(COMMENT | ws)
| .result;
</syntaxhighlight>
====The Task====
<syntaxhighlight lang=jq>
# For handling hex character codes &#x
def hex2i:
def toi: if . >= 87 then .-87 else . - 48 end;
reduce ( ascii_downcase | explode | map(toi) | reverse[]) as $i ([1, 0]; # [power, sum]
.[1] += $i * .[0]
| .[0] *= 16 )
| .[1];
 
def hexcode2json:
gsub("&#x(?<x>....);" ; .x | [hex2i] | implode) ;
 
def jsonify:
walk( if type == "array"
then map(select(type == "string" and test("^\n *$") | not))
elif type == "string" then hexcode2json
else . end);
 
# First convert to JSON ...
XML | jsonify
# ... and then extract Student Names
| .[]
| (.Students[].Student[]["@attributes"] // empty).Name
</syntaxhighlight>
'''Invocation''': jq -Rrs -f xml.jq students.xml
{{output}}
As above.
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using LightXML
 
let docstr = """<Students>
Line 1,867 ⟶ 2,242:
println(attribute(elem, "Name"))
end
end</langsyntaxhighlight>
 
{{out}}
Line 1,878 ⟶ 2,253:
=={{header|Kotlin}}==
As this is just a small XML document, the DOM parser has been used rather than the SAX parser:
<langsyntaxhighlight lang="scala">// version 1.1.3
 
import javax.xml.parsers.DocumentBuilderFactory
Line 1,913 ⟶ 2,288:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,926 ⟶ 2,301:
=={{header|Lasso}}==
Task calls for a result not using Xpaths. Thus two examples shown. First uses Xpath, second uses regular expression.
<langsyntaxhighlight Lassolang="lasso">// makes extracting attribute values easier
define xml_attrmap(in::xml_namedNodeMap_attr) => {
local(out = map)
Line 1,956 ⟶ 2,331:
}
#names -> join('<br />')
</syntaxhighlight>
</lang>
<langsyntaxhighlight Lassolang="lasso">// not using XML or Xpath
'<hr />'
local(
Line 1,967 ⟶ 2,342:
#names -> insert(#regexp -> matchstring(1))
}
#names -> join('<br />')</langsyntaxhighlight>
Output:
<pre>April
Line 1,982 ⟶ 2,357:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">q = QUOTE
r = RETURN
xml = "<Students>"&r&\
Line 1,999 ⟶ 2,374:
repeat with c in res.child
put c.attributes.name
end repeat</langsyntaxhighlight>
 
{{out}}
Line 2,012 ⟶ 2,387:
=={{header|LiveCode}}==
Put the XML text in a text field called FieldXML for this exercise.
<langsyntaxhighlight LiveCodelang="livecode">put revXMLCreateTree(fld "FieldXML",true,true,false) into currTree
put revXMLAttributeValues(currTree,"Students","Student","Name",return,-1)</langsyntaxhighlight>
 
=={{header|Lua}}==
Requires LuaExpat
<langsyntaxhighlight lang="lua">
require 'lxp'
data = [[<Students>
Line 2,037 ⟶ 2,412:
p:parse(data)
p:close()
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,050 ⟶ 2,425:
Declare Object Nothing is optional. COM objects deleted when module exit by default.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Const Enumerator=-4&
Line 2,077 ⟶ 2,452:
}
CheckIt
</syntaxhighlight>
</lang>
Using internal XML object
 
 
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
declare databank xmldata
method databank, "NumericCharactersEntities", true
with databank, "xml" as doc$, "beautify" as beautify
doc$={<?xml?>
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>
}
beautify=-4
Report 3, doc$
Method databank, "GetListByTag", "Student", -1 as Result
c=1 // Result is type of M2000 stack.
If len(Result)>0 then
Stack Result {
Read fieldsNo : With fieldsNo, "Attr" as fieldsno.tag$()
}
Stack Result {
Print c, " "+fieldsno.tag$("Name")
c++
// Loop raise a flag for this block,
// which interpreter read at the end of block, and then clear it
if empty else loop
Read fieldsNo
}
// this place hexadecimal value for char É
// this object offer by default 5 escaped characters: quot, amp, apos, lt, gt
// inner local function conv$() can be used to escape characters above 127.
fieldsno.tag$("Name")=@conv$("Émily")
Report 3, doc$
end if
 
declare databank Nothing
Function Conv$(a$)
if len(a$)=0 then exit function
local b$, c$, k
for i=1 to len(a$)
c$=mid$(a$, i,1)
k=uint(chrcode(c$))
if k>127 then b$+="&#x"+hex$(k,2)+";" else b$+=c$
next
=b$
End Function
}
CheckIt
</syntaxhighlight>
{{out}}
<pre>
Line 2,087 ⟶ 2,518:
</pre >
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Column[Cases[Import["test.xml","XML"],Rule["Name", n_ ] -> n,Infinity]]</langsyntaxhighlight>
{{out}}
Output:
<pre>April
April
Bob
Chad
Line 2,098 ⟶ 2,528:
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">RootXML = com.mathworks.xml.XMLUtils.createDocument('Students');
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Student');
Line 2,140 ⟶ 2,570:
for I=0:1:RootXML.getElementsByTagName('Student').getLength-1
disp(RootXML.getElementsByTagName('Student').item(I).getAttributes.item(tag).getValue)
end</langsyntaxhighlight>
 
{{out}}
Line 2,152 ⟶ 2,582:
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
XML/Input in Neko
Tectonics:
Line 2,181 ⟶ 2,611:
parse_xml(xmlString, events);
 
/* Entities are not converted, use external recode program for that */</langsyntaxhighlight>
 
{{out}}
<pre>
prompt$ nekoc xml-input.neko
prompt$ neko xml-input.n</pre><langsyntaxhighlight lang="xml">April
Bob
Chad
Dave
&#x00C9;mily</langsyntaxhighlight>
<pre>
prompt$ neko xml-input.n | recode html
Line 2,200 ⟶ 2,630:
 
=={{header|newLISP}}==
<langsyntaxhighlight lang="newlisp">
(set 'xml-input "<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
Line 2,216 ⟶ 2,646:
(if (= (length x) 6)
(println (last (sexp (chop x))))))
</syntaxhighlight>
</lang>
 
Output:
Line 2,227 ⟶ 2,657:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import xmlparser, xmltree, streams
 
let doc = newStringStream """<Students>
Line 2,240 ⟶ 2,670:
 
for i in doc.parseXml.findAll "Student":
echo i.attr "Name"</langsyntaxhighlight>
Output:
<pre>April
Line 2,249 ⟶ 2,679:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use XML;
 
Line 2,277 ⟶ 2,707:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
from the toplevel using the library [http://tech.motion-twin.com/xmllight.html xml-light]:
<langsyntaxhighlight lang="ocaml"># #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;
# #load "xml-light.cma" ;;
 
Line 2,305 ⟶ 2,735:
Dave
&#x00C9;mily
- : unit = ()</langsyntaxhighlight>
 
Another solution using the library [http://erratique.ch/software/xmlm xmlm]:
<langsyntaxhighlight lang="ocaml">#directory "+xmlm"
#load "xmlm.cmo"
open Xmlm
Line 2,332 ⟶ 2,762:
List.iter (function ((_, "Name"), name) -> print_endline name | _ -> ()) attrs
| _ -> ()
done</langsyntaxhighlight>
 
using the [http://www.xs4all.nl/~mmzeeman/ocaml/ ocaml expat wrapper]:
 
<langsyntaxhighlight lang="ocaml">open Expat
 
let xml_str = "
Line 2,357 ⟶ 2,787:
);
parse p xml_str;
final p;</langsyntaxhighlight>
 
=={{header|OpenEdge ABL/Progress 4GL}}==
 
<syntaxhighlight lang="openedgeabl">
<lang OpenEdgeABL>
/** ==== Definitions ===== **/
DEFINE VARIABLE chXMLString AS LONGCHAR NO-UNDO.
Line 2,391 ⟶ 2,821:
END.
 
</syntaxhighlight>
</lang>
 
=={{header|OpenEdge/Progress}}==
The following example uses the X-DOCUMENT DOM parser. For larger documents the SAX parser is recommended.
 
<langsyntaxhighlight lang="progress">
DEF VAR lcc AS LONGCHAR.
DEF VAR hxdoc AS HANDLE.
Line 2,432 ⟶ 2,862:
DELETE OBJECT hxdoc.
 
MESSAGE cstudents VIEW-AS ALERT-BOX.</langsyntaxhighlight>
 
'''Output:'''
Line 2,450 ⟶ 2,880:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Parser = {New XMLParser.parser init}
Line 2,481 ⟶ 2,911:
StudentNames = {Map Students GetStudentName}
in
{ForAll StudentNames System.showInfo}</langsyntaxhighlight>
 
=={{header|Perl}}==
{{libheader|XML::Simple}}
<langsyntaxhighlight lang="perl">use utf8;
use XML::Simple;
 
Line 2,498 ⟶ 2,928:
</Students>');
 
print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}});</langsyntaxhighlight>
{{out}}
<pre>April
Line 2,507 ⟶ 2,937:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include builtins/xml.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant xml = """
<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>
<Students>
<span style="color: #008080;">constant</span> <span style="color: #000000;">xml</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
&lt;Students&gt;
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
< &lt;Student Name="ChadApril" Gender="MF" DateOfBirth="19911989-0501-0602" />&gt;
< &lt;Student Name="DaveBob" Gender="M" DateOfBirth="19921990-0703-0804"> /&gt;
&lt;Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /&gt;
<Pet Type="dog" Name="Rover" />
&lt;Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"&gt;
</Student>
<Student DateOfBirth="1993-09-10" Gender &lt;Pet Type="Fdog" Name="&#x00C9;milyRover" />&gt;
&lt;/Student&gt;
</Students>
&lt;Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /&gt;
"""
&lt;/Students&gt;
sequence x = xml_parse(xml)
"""</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xml_parse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xml</span><span style="color: #0000FF;">)</span>
procedure traverse(sequence x)
if x[XML_TAGNAME]="Student" then
<span style="color: #008080;">procedure</span> <span style="color: #000000;">traverse</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
?xml_get_attribute(x,"Name")
<span style="color: #008080;">if</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">XML_TAGNAME</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">"Student"</span> <span style="color: #008080;">then</span>
else
<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: #000000;">xml_get_attribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Name"</span><span style="color: #0000FF;">),</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
x = x[XML_CONTENTS]
<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;">"\n"</span><span style="color: #0000FF;">)</span>
if not string(x) then
<span style="color: #008080;">else</span>
for i=1 to length(x) do
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">XML_CONTENTS</span><span style="color: #0000FF;">]</span>
traverse(x[i])
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #004080;">string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end for
<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;">x</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end if
<span style="color: #000000;">traverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
traverse(x[XML_CONTENTS])</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">traverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">XML_CONTENTS</span><span style="color: #0000FF;">])</span>
<!--</syntaxhighlight>-->
{{out}}
(noteNote the last line (&#x00C9;mily) looks significantly better on this page, and on Linux or when run in a browser, than it (usually) does on a windows console!)<br>
You may need to code the constant using Name="&amp;#x00C9;mily", but hopefully not, and not that doing so magically fixes the windows console.<br>
The puts() has been broken in two specifically for running in a browser, so it doesn't look like that ("&amp;"'d), and we ''don't'' want a false on the \n (ie ''do'' map that to &lt;br&gt;).
<pre>
"April"
Line 2,545 ⟶ 2,981:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
$data = '<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 2,560 ⟶ 2,996:
if ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' )
echo $xml->getAttribute('Name') . "\n";
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/xm.l")
 
(mapcar
'((L) (attr L 'Name))
(body (in "file.xml" (xml))) )</langsyntaxhighlight>
Output:
<pre>-> ("April" "Bob" "Chad" "Dave" "Émily")</pre>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
string in = "<Students>\n"
" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
Line 2,591 ⟶ 3,027:
collect += ({ node->get_attributes()->Name });
});
write("%{%s\n%}", collect);</langsyntaxhighlight>
 
Output:
Line 2,601 ⟶ 3,037:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang Powershell>
[xml]$xml = @'
<Students>
Line 2,618 ⟶ 3,054:
 
 
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Uses a PureBasic XML library (which is linked automatically) that is based on the library [http://expat.sourceforge.net/ expat XML parser] licensed under the MIT license.
<langsyntaxhighlight PureBasiclang="purebasic">Define studentNames.String, src$
 
src$ = "<Students>"
Line 2,671 ⟶ 3,107:
MessageRequester("Student Names", studentNames\s)
FreeXML(0)
EndIf </langsyntaxhighlight>
Sample output:
<pre>
Line 2,682 ⟶ 3,118:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import xml.dom.minidom
 
doc = """<Students>
Line 2,697 ⟶ 3,133:
 
for i in doc.getElementsByTagName("Student"):
print i.getAttribute("Name")</langsyntaxhighlight>
 
=={{header|R}}==
{{libheader|XML}}
<langsyntaxhighlight Rlang="r">library(XML)
#Read in XML string
str <- readLines(tc <- textConnection('<Students>
Line 2,713 ⟶ 3,149:
</Students>'))
close(tc)
str</langsyntaxhighlight>
[1] "<Students>"
[2] " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"
Line 2,723 ⟶ 3,159:
[8] " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />"
[9] "</Students>"
<langsyntaxhighlight Rlang="r">#Convert to an XML tree
xmltree <- xmlTreeParse(str)
 
Line 2,740 ⟶ 3,176:
#Change the encoding so that Emily displays correctly
Encoding(studentsnames) <- "UTF-8"
studentsnames</langsyntaxhighlight>
[1] "April" "Bob" "Chad" "Dave" "Émily"i
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(require xml xml/path)
Line 2,769 ⟶ 3,205:
(se-path*/list '(Student #:Name) students)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,776 ⟶ 3,212:
 
{{libheader|XML}}
<syntaxhighlight lang="raku" perl6line>use XML;
 
my $xml = from-xml '<Students>
Line 2,788 ⟶ 3,224:
</Students>';
 
say .<Name> for $xml.nodes.grep(/Student/)</langsyntaxhighlight>
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">import lang::xml::DOM;
 
public void getNames(loc a){
Line 2,798 ⟶ 3,234:
case element(_,"Student",[_*,attribute(_,"Name", x),_*]): println(x);
};
}</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="rascal">rascal>getNames(|file:///Users/.../Desktop/xmlinput.xml|)
April
Bob
Line 2,806 ⟶ 3,242:
Dave
Émily
ok</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "XML Reading"
URL: http://rosettacode.org/wiki/XML_Reading
Line 2,843 ⟶ 3,279:
print select student/2 "Name"
]
]</langsyntaxhighlight>
 
Output:
Line 2,855 ⟶ 3,291:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX program extracts student names from an XML string(s). */
g.=
g.1 = '<Students> '
Line 2,871 ⟶ 3,307:
parse var g.j 'Name="' studname '"'
if studname\=='' then say studname
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) input:}}
<pre>
Line 2,884 ⟶ 3,320:
===version 2===
This REXX version handles more HTML tags for output.
<langsyntaxhighlight lang="rexx">/*REXX program extracts student names from an XML string(s). */
g.=
g.1 = '<Students> '
Line 2,968 ⟶ 3,404:
$=XML_('£',"pound") ; $=XML_('╦',"boxHD") ; $=XML_('²',"sup2") ; $=XML_('é','#x00e9')
$=XML_('¥',"yen") ; $=XML_('╠',"boxVR") ; $=XML_('■',"square ") ; $=XML_('â',"acirc")
return $</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
 
Line 2,983 ⟶ 3,419:
=={{header|Ruby}}==
{{libheader|REXML}}
<langsyntaxhighlight lang="ruby">require 'rexml/document'
include REXML
 
Line 2,996 ⟶ 3,432:
 
# using xpath
doc.each_element("*/Student") {|node| puts node.attributes["Name"]}</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">' ------------------------------------------------------------------------
'XMLPARSER methods
 
Line 3,042 ⟶ 3,478:
print count;" ";#spy value$();" ->";#spy ATTRIBVALUE$(1)
next count</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 3,049 ⟶ 3,485:
This implementation uses [https://crates.io/crates/xml-rs xml-rs], which provides a streaming reader API.
 
<langsyntaxhighlight lang="rust">extern crate xml; // provided by the xml-rs crate
use xml::{name::OwnedName, reader::EventReader, reader::XmlEvent};
 
Line 3,085 ⟶ 3,521:
}
Ok(())
}</langsyntaxhighlight>
 
{{out}}
Line 3,101 ⟶ 3,537:
This DOM can then be iterated in a convenient fashion.
 
<langsyntaxhighlight lang="rust">extern crate roxmltree;
 
const DOCUMENT: &str = r#"
Line 3,128 ⟶ 3,564:
Ok(())
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,143 ⟶ 3,579:
Scala has native XML support, with query constructs similar to XPath and XQuery.
 
<langsyntaxhighlight lang="scala">val students =
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 3,154 ⟶ 3,590:
</Students>
 
students \ "Student" \\ "@Name" foreach println</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">require('XML::Simple');
 
var ref = %S'XML::Simple'.XMLin('<Students>
Line 3,170 ⟶ 3,606:
</Students>');
 
ref{:Student}.each { say _{:Name} };</langsyntaxhighlight>
{{out}}
<pre>
Line 3,184 ⟶ 3,620:
Slate's XML Reader is still being developed at the time of this writing.
<langsyntaxhighlight lang="slate">slate[1]> [ |tree|
 
tree: (Xml SimpleParser newOn: '<Students>
Line 3,204 ⟶ 3,640:
Dave
&#x00C9;mily
Nil</langsyntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
import Foundation
 
let xmlString = """
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>
"""
if let xmlData = xmlString.data(using: .utf8) {
do {
let doc = try XMLDocument(data: xmlData)
print("Using XPath:")
for node in try doc.nodes(forXPath: "/Students/Student/@Name") {
guard let name = node.stringValue else { continue }
print(name)
}
print("Using node walk")
if let root = doc.rootElement() {
for child in root.elements(forName: "Student") {
guard let name = child.attribute(forName: "Name")?.stringValue else { continue }
print(name)
}
}
} catch {
debugPrint(error)
}
}
</syntaxhighlight>
Output:
<syntaxhighlight lang="shell">
~ % ./XMLInput
Using XPath:
April
Bob
Chad
Dave
Émily
Using node walk
April
Bob
Chad
Dave
Émily
</syntaxhighlight>
 
=={{header|Tcl}}==
Using {{libheader|tDOM}}
<langsyntaxhighlight lang="tcl">package require tdom
set tree [dom parse $xml]
set studentNodes [$tree getElementsByTagName Student] ;# or: set studentNodes [[$tree documentElement] childNodes]
Line 3,214 ⟶ 3,702:
foreach node $studentNodes {
puts [$node getAttribute Name]
}</langsyntaxhighlight>
Using {{libheader|TclXML}}
<langsyntaxhighlight lang="tcl">package require xml
set parser [xml::parser -elementstartcommand elem]
proc elem {name attlist args} {
Line 3,223 ⟶ 3,711:
}
}
$parser parse $xml</langsyntaxhighlight>
 
Using just pure-Tcl (originally on http://wiki.tcl.tk/3919):
<langsyntaxhighlight Tcllang="tcl">proc xml2list xml {
regsub -all {>\s*<} [string trim $xml " \n\t<>"] "\} \{" xml
set xml [string map {> "\} \{#text \{" < "\}\} \{"} $xml]
Line 3,276 ⟶ 3,764:
}
}
}</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
MODE DATA
Line 3,301 ⟶ 3,789:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,316 ⟶ 3,804:
The name Émily is properly converted from the HTML/XML escape syntax.
 
<langsyntaxhighlight lang="txr"><Students>
@(collect :vars (NAME GENDER YEAR MONTH DAY (PET_TYPE "none") (PET_NAME "")))
@ (cases)
Line 3,334 ⟶ 3,822:
@{NAME 12} @GENDER @YEAR-@MONTH-@DAY @PET_TYPE @PET_NAME
@ (end)
@(end)</langsyntaxhighlight>
 
Sample run:
Line 3,347 ⟶ 3,835:
To obtain the output specified in this task, we can simply reduce the @(output) block to this:
 
<langsyntaxhighlight lang="txr">@(output :filter :from_html)
@NAME
@(end)</langsyntaxhighlight>
 
<pre>
Line 3,359 ⟶ 3,847:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Const strXml As String = "" & _
Line 3,386 ⟶ 3,874:
End If
Set myNodes = Nothing
End Sub</langsyntaxhighlight>
{{out}}
<pre>April
Line 3,396 ⟶ 3,884:
=={{header|Vedit macro language}}==
This implementation finds all ''Student'' tags and then displays the contents of their ''Name'' parameter.
<langsyntaxhighlight lang="vedit">Repeat(ALL) {
Search("<Student|X", ERRBREAK)
#1 = Cur_Pos
Line 3,405 ⟶ 3,893:
Type_Block(#2, Cur_Pos)
Type_Newline
}</langsyntaxhighlight>
 
Output:
Line 3,415 ⟶ 3,903:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Dim xml = <Students>
<Student Name="April"/>
<Student Name="Bob"/>
Line 3,427 ⟶ 3,915:
For Each name In names
Console.WriteLine(name)
Next</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 3,433 ⟶ 3,921:
{{libheader|Wren-fmt}}
Wren doesn't currently have an XML parser though we don't really need one for this task as string pattern matching is sufficient to extract the student names.
<langsyntaxhighlight ecmascriptlang="wren">import "./pattern" for Pattern
import "./fmt" for Conv
 
var xml =
Line 3,466 ⟶ 3,954:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,476 ⟶ 3,964:
Émily
</pre>
<br>
{{libheader|Wren-xsequence}}
Since the first version was written, the above XML parser has appeared and support for 'raw' strings has also been added to the language. Consequently, the solution can now be rewritten as follows, the output being the same as before.
<syntaxhighlight lang="wren">import "./xsequence" for XDocument
 
var xml = """
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" />
</Students>
"""
var doc = XDocument.parse(xml)
var names = doc.root.elements("Student").map { |el| el.attribute("Name").value }.toList
System.print(names.join("\n"))</syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9; \intrinsic routines
string 0; \use zero-terminated strings
 
Line 3,522 ⟶ 4,029:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,534 ⟶ 4,041:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">// ========== routine for set code conversion ================
 
data 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238
Line 3,601 ⟶ 4,108:
name$ = convASCII$(mid$(xml$, p, p2 - p), "&#x")
print name$
loop</langsyntaxhighlight>
 
=={{header|zkl}}==
Uses regular expressions and the data is in a file identical to task description.<br/>
Assumes: a name attribute is complete in a line and only one name per line.
<langsyntaxhighlight lang="zkl">student:=RegExp(0'|.*<Student\s*.+Name\s*=\s*"([^"]+)"|);
unicode:=RegExp(0'|.*(&#x[0-9a-fA-F]+;)|);
xml:=File("foo.xml").read();
Line 3,623 ⟶ 4,130:
});
 
students.println();</langsyntaxhighlight>
{{out}}<pre>L("April","Bob","Chad","Dave","Émily")</pre>
 
9,476

edits