XML/Input: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Wren}}: Minor tidy) |
|||
(17 intermediate revisions by 9 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]].
<
<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="Émily" />
</Students></
Expected Output
Line 22:
=={{header|8th}}==
<
\ 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>
{{out}}
April<br>
Line 56:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputXml64.s */
Line 275:
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 287:
=={{header|ActionScript}}==
<
{
import flash.display.Sprite;
Line 308:
}
}
}</
=={{header|Ada}}==
Line 316:
extract_students.adb:
<
with Input_Sources.Strings;
with Unicode.CES.Utf8;
Line 338:
My_Reader.Parse (Reader, Input);
Input_Sources.Strings.Close (Input);
end Extract_Students;</
my_reader.ads:
<
with Sax.Readers;
with Unicode.CES;
Line 352:
Qname : Unicode.CES.Byte_Sequence := "";
Atts : Sax.Attributes.Attributes'Class);
end My_Reader;</
my_reader.adb:
<
package body My_Reader is
procedure Start_Element
Line 368:
end if;
end Start_Element;
end My_Reader;</
Output:
Line 378:
===Alternative using a DOM document===
<
with Sax.Readers;
with Input_Sources.Strings;
Line 418:
end loop;
DOM.Readers.Free (Reader);
end Extract_Students;</
output is the same.
Line 428:
main.adb:
<
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;</
handlers.ads:
<
with XML.SAX.Attributes;
with XML.SAX.Content_Handlers;
Line 467:
(Self : Handler) return League.Strings.Universal_String;
end Handlers;</
handlers.adb:
<
package body Handlers is
Line 509:
end Start_Element;
end Handlers;</
=={{header|Aikido}}==
Put the XML in the file called t.xml
<
import xml
Line 529:
}
</syntaxhighlight>
The output is (Aikido doesn't support unicode rendering):
April
Line 539:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program inputXml.s */
Line 821:
pop {r1-r4}
bx lr
</syntaxhighlight>
{{output}}
<pre>
Line 834:
=={{header|Arturo}}==
<
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 847:
students: read.xml data
print join.with:"\n" map students 'student -> student\Name</
{{out}}
Line 859:
=={{header|AutoHotkey}}==
simply using regular expressions
<
(
<Students>
Line 878:
names .= name1 . "`n"
msgbox % names</
=={{header|AWK}}==
The following code extracts the value of the property "Name" from every Student tag. It does not handle the <tt>&#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.
<
{
if ( match(buffer, /<Student[ \t]+[^>]*Name[ \t]*=[ \t]*"([^"]*)"/, mt) != 0 ) {
Line 938:
print k
}
}</
Using [http://awk.info/?getxml getXML.awk] written by Jan Weber, one could do this:
{{works with|gawk}} or {{works with|nawk}}
<
$1 == "TAG" {tag = $2}
tag == "Student" && /Name=/ {print substr($0, index($0, "=") + 1)}
'</
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}}
<
$1 == "begin" {tag = $2}
$1 == "attrib" {attrib = $2}
$1 == "value" && tag == "STUDENT" && attrib == "name" {print $2}
'</
Both of these produce this output
Line 975:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
xmlfile$ = "C:\students.xml"
PROC_initXML(xmlobj{}, xmlfile$)
Line 994:
UNTIL FN_getLevel(xmlobj{}) < level%
PROC_exitXML(xmlobj{})</
Output:
<pre>
Line 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:
<
& ( get$("students.xml",X,ML)
: ?
Line 1,021:
| !names
)
)</
Alternative solution, reading input from memory:
<
& ( get
$ ( "<Students>
Line 1,050:
| !names
)
)</
Output:
<pre>April Bob Chad Dave Émily</pre>
Line 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}}
<
#include <stdlib.h>
#include <string.h>
Line 1,106:
xmlCleanupParser();
return 0;
}</
==={{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], "É","É" ) );
/* 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="Émily" />
</Students></syntaxhighlight>
=={{header|C sharp}}==
<
class Program
{
Line 1,125 ⟶ 1,207:
}
}
</syntaxhighlight>
=={{header|C++}}==
Line 1,132 ⟶ 1,214:
{{uses from|Library|Qt|component1=QDomDocument|component2=QObject|component3=QDomElement}}
<
Using the Qt library's XML parser.
*/
Line 1,161 ⟶ 1,243:
}
return 0;
}</
=={{header|Caché ObjectScript}}==
<
{
Line 1,200 ⟶ 1,282:
}
}</
{{out|Examples}}
<pre>
Line 1,215 ⟶ 1,297:
{{uses from|Library|clojure.xml|component1=parse}}
This version uses the standard Clojure function ''xml-seq'
<
(import '(java.io ByteArrayInputStream))
(use 'clojure.xml) ; defines 'parse
Line 1,230 ⟶ 1,312:
(def students (parse (-> xml-text .getBytes ByteArrayInputStream.)))
</syntaxhighlight>
The parse produces a data structure where each element is represented as a map with '':tag'', '':attrs'', and '':content'' keys.
Line 1,236 ⟶ 1,318:
''xml-seq'' produces a sequence of such nodes by walking the resulting tree.
<
(doseq [{:keys [tag attrs]} (xml-seq students)]
(if (= :Student tag)
(println (:Name attrs))))
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 1,246 ⟶ 1,328:
{{libheader|Closure XML}}
<
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
Line 1,262 ⟶ 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))))</
produces<
=={{header|D}}==
{{libheader|KXML}}
<
char[]xmlinput =
"<Students>
Line 1,291 ⟶ 1,373:
break;
}
}</
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
//You need to use these units
uses
Line 1,341 ⟶ 1,423:
Showmessage(GetStudents(XMLInput));
end;
</syntaxhighlight>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( xml_input ).
Line 1,367 ⟶ 1,449:
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>".
</syntaxhighlight>
{{out}}
<pre>
Line 1,379 ⟶ 1,461:
=={{header|F_Sharp|F#}}==
<
open System.Xml
open System.Xml.Linq
Line 1,404 ⟶ 1,486:
let names = students.Attributes <| xn "Name"
Seq.iter ((fun (a : XAttribute) -> a.Value) >> printfn "%s") names
0</
=={{header|Factor}}==
<
: print-student-names ( string -- )
Line 1,420 ⟶ 1,502:
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>]] print-student-names</
=={{header|Fantom}}==
<
using xml
Line 1,442 ⟶ 1,524:
}
}
</syntaxhighlight>
=={{header|Forth}}==
Line 1,448 ⟶ 1,530:
{{libheader|Forth Foundation Library}}
<
include ffl/str.fs
include ffl/xis.fs
Line 1,495 ⟶ 1,577:
;
xmlparse</
=={{header|Fortran}}==
Line 1,503 ⟶ 1,585:
Uses [https://github.com/DLR-SC/tixi tixi library] (+ LibXML, curl as dependencies)
<
program tixi_rosetta
use tixi
Line 1,537 ⟶ 1,619:
end program tixi_rosetta
</syntaxhighlight>
Compile
Line 1,557 ⟶ 1,639:
Uses [https://github.com/andreww/fox FoX]
<
program fox_rosetta
use FoX_dom
Line 1,587 ⟶ 1,669:
call destroy(doc)
end program fox_rosetta
</syntaxhighlight>
Output
Line 1,597 ⟶ 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=\'É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
É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=\"É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.
<
import (
Line 1,650 ⟶ 1,867:
fmt.Println(s.Name)
}
}</
{{out}}
<pre>
Line 1,661 ⟶ 1,878:
=={{header|Groovy}}==
<
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
Line 1,672 ⟶ 1,889:
def students = new XmlParser().parseText(input)
students.each { println it.'@Name' }</
=={{header|Haskell}}==
<
import Text.XML.Light
Line 1,689 ⟶ 1,906:
xmlRead elm name = mapM_ putStrLn
. concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm))
. onlyElems. parseXML</
Show names:
<
April
Bob
Chad
Dave
Émily</
=={{header|HicEst}}==
<
READ(ClipBoard) in
EDIT(Text=in, SPR='"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO)</
<pre>out is returned as:
April Bob Chad Dave Émily
Line 1,710 ⟶ 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:
<
saxclass 'Students'
Line 1,716 ⟶ 1,933:
cocurrent'base'
process_Students_ XML</
April
Bob
Line 1,724 ⟶ 1,941:
and the definition of the variable <code>XML</code>:
<
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 1,734 ⟶ 1,951:
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
)</
=={{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}}
<
import java.io.StringReader;
import org.xml.sax.Attributes;
Line 1,789 ⟶ 2,006:
}
}
}</
=={{header|JavaScript}}==
Line 1,795 ⟶ 2,012:
=== Browser version ===
This version tested against Chrome 37, Firefox 32, and IE 11:
<syntaxhighlight lang="javascript">
var xmlstr = '<Students>' +
'<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
Line 1,822 ⟶ 2,039:
console.log(students[e].attributes.Name.value);
}
</syntaxhighlight>
{{works with|Mozilla Firefox|32}}
=== Node.js version ===
<syntaxhighlight lang="javascript">
var parseString = require('xml2js').parseString;
var xmlstr = '<Students>' +
Line 1,845 ⟶ 2,062:
}
});
</syntaxhighlight>
=== E4X version ===
Alternatively, use the E4X featureset (currently only in Firefox):
<syntaxhighlight lang="javascript">
var xmlstr = '<Students>' +
'<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />' +
Line 1,870 ⟶ 2,087:
alert(output);
</syntaxhighlight>
=={{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. "É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}}
<
let docstr = """<Students>
Line 1,892 ⟶ 2,242:
println(attribute(elem, "Name"))
end
end</
{{out}}
Line 1,903 ⟶ 2,253:
=={{header|Kotlin}}==
As this is just a small XML document, the DOM parser has been used rather than the SAX parser:
<
import javax.xml.parsers.DocumentBuilderFactory
Line 1,938 ⟶ 2,288:
}
}
}</
{{out}}
Line 1,951 ⟶ 2,301:
=={{header|Lasso}}==
Task calls for a result not using Xpaths. Thus two examples shown. First uses Xpath, second uses regular expression.
<
define xml_attrmap(in::xml_namedNodeMap_attr) => {
local(out = map)
Line 1,981 ⟶ 2,331:
}
#names -> join('<br />')
</syntaxhighlight>
<
'<hr />'
local(
Line 1,992 ⟶ 2,342:
#names -> insert(#regexp -> matchstring(1))
}
#names -> join('<br />')</
Output:
<pre>April
Line 2,007 ⟶ 2,357:
=={{header|Lingo}}==
<
r = RETURN
xml = "<Students>"&r&\
Line 2,024 ⟶ 2,374:
repeat with c in res.child
put c.attributes.name
end repeat</
{{out}}
Line 2,037 ⟶ 2,387:
=={{header|LiveCode}}==
Put the XML text in a text field called FieldXML for this exercise.
<
put revXMLAttributeValues(currTree,"Students","Student","Name",return,-1)</
=={{header|Lua}}==
Requires LuaExpat
<
require 'lxp'
data = [[<Students>
Line 2,062 ⟶ 2,412:
p:parse(data)
p:close()
</syntaxhighlight>
Output:
<pre>
Line 2,075 ⟶ 2,425:
Declare Object Nothing is optional. COM objects deleted when module exit by default.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Const Enumerator=-4&
Line 2,102 ⟶ 2,452:
}
CheckIt
</syntaxhighlight>
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="É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,113 ⟶ 2,519:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre>April
Line 2,122 ⟶ 2,528:
=={{header|MATLAB}}==
<
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Student');
Line 2,164 ⟶ 2,570:
for I=0:1:RootXML.getElementsByTagName('Student').getLength-1
disp(RootXML.getElementsByTagName('Student').item(I).getAttributes.item(tag).getValue)
end</
{{out}}
Line 2,176 ⟶ 2,582:
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
XML/Input in Neko
Tectonics:
Line 2,205 ⟶ 2,611:
parse_xml(xmlString, events);
/* Entities are not converted, use external recode program for that */</
{{out}}
<pre>
prompt$ nekoc xml-input.neko
prompt$ neko xml-input.n</pre><
Bob
Chad
Dave
Émily</
<pre>
prompt$ neko xml-input.n | recode html
Line 2,224 ⟶ 2,630:
=={{header|newLISP}}==
<
(set 'xml-input "<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
Line 2,240 ⟶ 2,646:
(if (= (length x) 6)
(println (last (sexp (chop x))))))
</syntaxhighlight>
Output:
Line 2,251 ⟶ 2,657:
=={{header|Nim}}==
<
let doc = newStringStream """<Students>
Line 2,264 ⟶ 2,670:
for i in doc.parseXml.findAll "Student":
echo i.attr "Name"</
Output:
<pre>April
Line 2,273 ⟶ 2,679:
=={{header|Objeck}}==
<
use XML;
Line 2,301 ⟶ 2,707:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
from the toplevel using the library [http://tech.motion-twin.com/xmllight.html xml-light]:
<
# #load "xml-light.cma" ;;
Line 2,329 ⟶ 2,735:
Dave
Émily
- : unit = ()</
Another solution using the library [http://erratique.ch/software/xmlm xmlm]:
<
#load "xmlm.cmo"
open Xmlm
Line 2,356 ⟶ 2,762:
List.iter (function ((_, "Name"), name) -> print_endline name | _ -> ()) attrs
| _ -> ()
done</
using the [http://www.xs4all.nl/~mmzeeman/ocaml/ ocaml expat wrapper]:
<
let xml_str = "
Line 2,381 ⟶ 2,787:
);
parse p xml_str;
final p;</
=={{header|OpenEdge ABL/Progress 4GL}}==
<syntaxhighlight lang="openedgeabl">
/** ==== Definitions ===== **/
DEFINE VARIABLE chXMLString AS LONGCHAR NO-UNDO.
Line 2,415 ⟶ 2,821:
END.
</syntaxhighlight>
=={{header|OpenEdge/Progress}}==
The following example uses the X-DOCUMENT DOM parser. For larger documents the SAX parser is recommended.
<
DEF VAR lcc AS LONGCHAR.
DEF VAR hxdoc AS HANDLE.
Line 2,456 ⟶ 2,862:
DELETE OBJECT hxdoc.
MESSAGE cstudents VIEW-AS ALERT-BOX.</
'''Output:'''
Line 2,474 ⟶ 2,880:
=={{header|Oz}}==
<
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Parser = {New XMLParser.parser init}
Line 2,505 ⟶ 2,911:
StudentNames = {Map Students GetStudentName}
in
{ForAll StudentNames System.showInfo}</
=={{header|Perl}}==
{{libheader|XML::Simple}}
<
use XML::Simple;
Line 2,522 ⟶ 2,928:
</Students>');
print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}});</
{{out}}
<pre>April
Line 2,531 ⟶ 2,937:
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
<Students>
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
"""</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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">else</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<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}}
You may need to code the constant using Name="&#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 ("&"'d), and we ''don't'' want a false on the \n (ie ''do'' map that to <br>).
<pre>
"April"
Line 2,569 ⟶ 2,981:
=={{header|PHP}}==
<
$data = '<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 2,584 ⟶ 2,996:
if ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' )
echo $xml->getAttribute('Name') . "\n";
?></
=={{header|PicoLisp}}==
<
(mapcar
'((L) (attr L 'Name))
(body (in "file.xml" (xml))) )</
Output:
<pre>-> ("April" "Bob" "Chad" "Dave" "Émily")</pre>
=={{header|Pike}}==
<syntaxhighlight lang="pike">
string in = "<Students>\n"
" <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
Line 2,615 ⟶ 3,027:
collect += ({ node->get_attributes()->Name });
});
write("%{%s\n%}", collect);</
Output:
Line 2,625 ⟶ 3,037:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
[xml]$xml = @'
<Students>
Line 2,642 ⟶ 3,054:
</syntaxhighlight>
=={{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.
<
src$ = "<Students>"
Line 2,695 ⟶ 3,107:
MessageRequester("Student Names", studentNames\s)
FreeXML(0)
EndIf </
Sample output:
<pre>
Line 2,706 ⟶ 3,118:
=={{header|Python}}==
<
doc = """<Students>
Line 2,721 ⟶ 3,133:
for i in doc.getElementsByTagName("Student"):
print i.getAttribute("Name")</
=={{header|R}}==
{{libheader|XML}}
<
#Read in XML string
str <- readLines(tc <- textConnection('<Students>
Line 2,737 ⟶ 3,149:
</Students>'))
close(tc)
str</
[1] "<Students>"
[2] " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"
Line 2,747 ⟶ 3,159:
[8] " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />"
[9] "</Students>"
<
xmltree <- xmlTreeParse(str)
Line 2,764 ⟶ 3,176:
#Change the encoding so that Emily displays correctly
Encoding(studentsnames) <- "UTF-8"
studentsnames</
[1] "April" "Bob" "Chad" "Dave" "Émily"i
=={{header|Racket}}==
<
#lang racket
(require xml xml/path)
Line 2,793 ⟶ 3,205:
(se-path*/list '(Student #:Name) students)
</syntaxhighlight>
=={{header|Raku}}==
Line 2,800 ⟶ 3,212:
{{libheader|XML}}
<syntaxhighlight lang="raku"
my $xml = from-xml '<Students>
Line 2,812 ⟶ 3,224:
</Students>';
say .<Name> for $xml.nodes.grep(/Student/)</
=={{header|Rascal}}==
<
public void getNames(loc a){
Line 2,822 ⟶ 3,234:
case element(_,"Student",[_*,attribute(_,"Name", x),_*]): println(x);
};
}</
Output:
<
April
Bob
Line 2,830 ⟶ 3,242:
Dave
Émily
ok</
=={{header|REBOL}}==
<
Title: "XML Reading"
URL: http://rosettacode.org/wiki/XML_Reading
Line 2,867 ⟶ 3,279:
print select student/2 "Name"
]
]</
Output:
Line 2,879 ⟶ 3,291:
=={{header|REXX}}==
===version 1===
<
g.=
g.1 = '<Students> '
Line 2,895 ⟶ 3,307:
parse var g.j 'Name="' studname '"'
if studname\=='' then say studname
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default (internal) input:}}
<pre>
Line 2,908 ⟶ 3,320:
===version 2===
This REXX version handles more HTML tags for output.
<
g.=
g.1 = '<Students> '
Line 2,992 ⟶ 3,404:
$=XML_('£',"pound") ; $=XML_('╦',"boxHD") ; $=XML_('²',"sup2") ; $=XML_('é','#x00e9')
$=XML_('¥',"yen") ; $=XML_('╠',"boxVR") ; $=XML_('■',"square ") ; $=XML_('â',"acirc")
return $</
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]].
Line 3,007 ⟶ 3,419:
=={{header|Ruby}}==
{{libheader|REXML}}
<
include REXML
Line 3,020 ⟶ 3,432:
# using xpath
doc.each_element("*/Student") {|node| puts node.attributes["Name"]}</
=={{header|Run BASIC}}==
<
'XMLPARSER methods
Line 3,066 ⟶ 3,478:
print count;" ";#spy value$();" ->";#spy ATTRIBVALUE$(1)
next count</
=={{header|Rust}}==
Line 3,073 ⟶ 3,485:
This implementation uses [https://crates.io/crates/xml-rs xml-rs], which provides a streaming reader API.
<
use xml::{name::OwnedName, reader::EventReader, reader::XmlEvent};
Line 3,109 ⟶ 3,521:
}
Ok(())
}</
{{out}}
Line 3,125 ⟶ 3,537:
This DOM can then be iterated in a convenient fashion.
<
const DOCUMENT: &str = r#"
Line 3,152 ⟶ 3,564:
Ok(())
}
</syntaxhighlight>
{{out}}
Line 3,167 ⟶ 3,579:
Scala has native XML support, with query constructs similar to XPath and XQuery.
<
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 3,178 ⟶ 3,590:
</Students>
students \ "Student" \\ "@Name" foreach println</
=={{header|Sidef}}==
{{trans|Perl}}
<
var ref = %S'XML::Simple'.XMLin('<Students>
Line 3,194 ⟶ 3,606:
</Students>');
ref{:Student}.each { say _{:Name} };</
{{out}}
<pre>
Line 3,208 ⟶ 3,620:
Slate's XML Reader is still being developed at the time of this writing.
<
tree: (Xml SimpleParser newOn: '<Students>
Line 3,228 ⟶ 3,640:
Dave
Émily
Nil</
=={{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="É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}}
<
set tree [dom parse $xml]
set studentNodes [$tree getElementsByTagName Student] ;# or: set studentNodes [[$tree documentElement] childNodes]
Line 3,238 ⟶ 3,702:
foreach node $studentNodes {
puts [$node getAttribute Name]
}</
Using {{libheader|TclXML}}
<
set parser [xml::parser -elementstartcommand elem]
proc elem {name attlist args} {
Line 3,247 ⟶ 3,711:
}
}
$parser parse $xml</
Using just pure-Tcl (originally on http://wiki.tcl.tk/3919):
<
regsub -all {>\s*<} [string trim $xml " \n\t<>"] "\} \{" xml
set xml [string map {> "\} \{#text \{" < "\}\} \{"} $xml]
Line 3,300 ⟶ 3,764:
}
}
}</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
MODE DATA
Line 3,325 ⟶ 3,789:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
Output:
<pre>
Line 3,340 ⟶ 3,804:
The name Émily is properly converted from the HTML/XML escape syntax.
<
@(collect :vars (NAME GENDER YEAR MONTH DAY (PET_TYPE "none") (PET_NAME "")))
@ (cases)
Line 3,358 ⟶ 3,822:
@{NAME 12} @GENDER @YEAR-@MONTH-@DAY @PET_TYPE @PET_NAME
@ (end)
@(end)</
Sample run:
Line 3,371 ⟶ 3,835:
To obtain the output specified in this task, we can simply reduce the @(output) block to this:
<
@NAME
@(end)</
<pre>
Line 3,383 ⟶ 3,847:
=={{header|VBA}}==
<
Const strXml As String = "" & _
Line 3,410 ⟶ 3,874:
End If
Set myNodes = Nothing
End Sub</
{{out}}
<pre>April
Line 3,420 ⟶ 3,884:
=={{header|Vedit macro language}}==
This implementation finds all ''Student'' tags and then displays the contents of their ''Name'' parameter.
<
Search("<Student|X", ERRBREAK)
#1 = Cur_Pos
Line 3,429 ⟶ 3,893:
Type_Block(#2, Cur_Pos)
Type_Newline
}</
Output:
Line 3,439 ⟶ 3,903:
=={{header|Visual Basic .NET}}==
<
<Student Name="April"/>
<Student Name="Bob"/>
Line 3,451 ⟶ 3,915:
For Each name In names
Console.WriteLine(name)
Next</
=={{header|Wren}}==
Line 3,457 ⟶ 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.
<
import "./fmt" for Conv
var xml =
Line 3,490 ⟶ 3,954:
}
}
}</
{{out}}
Line 3,500 ⟶ 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="É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}}==
<
string 0; \use zero-terminated strings
Line 3,546 ⟶ 4,029:
CrLf(0);
];
]</
{{out}}
Line 3,558 ⟶ 4,041:
=={{header|Yabasic}}==
<
data 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238
Line 3,625 ⟶ 4,108:
name$ = convASCII$(mid$(xml$, p, p2 - p), "&#x")
print name$
loop</
=={{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.
<
unicode:=RegExp(0'|.*(&#x[0-9a-fA-F]+;)|);
xml:=File("foo.xml").read();
Line 3,647 ⟶ 4,130:
});
students.println();</
{{out}}<pre>L("April","Bob","Chad","Dave","Émily")</pre>
|