XML/Input: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Wren}}: Added a version using an XML library.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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,059:
{{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;
}</
=={{header|C sharp}}==
<
class Program
{
Line 1,125:
}
}
</syntaxhighlight>
=={{header|C++}}==
Line 1,132:
{{uses from|Library|Qt|component1=QDomDocument|component2=QObject|component3=QDomElement}}
<
Using the Qt library's XML parser.
*/
Line 1,161:
}
return 0;
}</
=={{header|Caché ObjectScript}}==
<
{
Line 1,200:
}
}</
{{out|Examples}}
<pre>
Line 1,215:
{{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:
(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:
''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:
{{libheader|Closure XML}}
<
"<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
Line 1,262:
(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:
break;
}
}</
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
//You need to use these units
uses
Line 1,341:
Showmessage(GetStudents(XMLInput));
end;
</syntaxhighlight>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( xml_input ).
Line 1,367:
<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />
</Students>".
</syntaxhighlight>
{{out}}
<pre>
Line 1,379:
=={{header|F_Sharp|F#}}==
<
open System.Xml
open System.Xml.Linq
Line 1,404:
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:
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>]] print-student-names</
=={{header|Fantom}}==
<
using xml
Line 1,442:
}
}
</syntaxhighlight>
=={{header|Forth}}==
Line 1,448:
{{libheader|Forth Foundation Library}}
<
include ffl/str.fs
include ffl/xis.fs
Line 1,495:
;
xmlparse</
=={{header|Fortran}}==
Line 1,503:
Uses [https://github.com/DLR-SC/tixi tixi library] (+ LibXML, curl as dependencies)
<
program tixi_rosetta
use tixi
Line 1,537:
end program tixi_rosetta
</syntaxhighlight>
Compile
Line 1,557:
Uses [https://github.com/andreww/fox FoX]
<
program fox_rosetta
use FoX_dom
Line 1,587:
call destroy(doc)
end program fox_rosetta
</syntaxhighlight>
Output
Line 1,601:
=={{header|Go}}==
Go's <tt>xml.Unmarshal</tt> uses reflection to fill in data-structures recursively.
<
import (
Line 1,650:
fmt.Println(s.Name)
}
}</
{{out}}
<pre>
Line 1,661:
=={{header|Groovy}}==
<
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
Line 1,672:
def students = new XmlParser().parseText(input)
students.each { println it.'@Name' }</
=={{header|Haskell}}==
<
import Text.XML.Light
Line 1,689:
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:
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:
cocurrent'base'
process_Students_ XML</
April
Bob
Line 1,724:
and the definition of the variable <code>XML</code>:
<
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 1,734:
<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:
}
}
}</
=={{header|JavaScript}}==
Line 1,795:
=== 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:
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:
}
});
</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:
alert(output);
</syntaxhighlight>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
let docstr = """<Students>
Line 1,892:
println(attribute(elem, "Name"))
end
end</
{{out}}
Line 1,903:
=={{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:
}
}
}</
{{out}}
Line 1,951:
=={{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:
}
#names -> join('<br />')
</syntaxhighlight>
<
'<hr />'
local(
Line 1,992:
#names -> insert(#regexp -> matchstring(1))
}
#names -> join('<br />')</
Output:
<pre>April
Line 2,007:
=={{header|Lingo}}==
<
r = RETURN
xml = "<Students>"&r&\
Line 2,024:
repeat with c in res.child
put c.attributes.name
end repeat</
{{out}}
Line 2,037:
=={{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:
p:parse(data)
p:close()
</syntaxhighlight>
Output:
<pre>
Line 2,075:
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:
}
CheckIt
</syntaxhighlight>
{{out}}
<pre>
Line 2,113:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre>April
Line 2,122:
=={{header|MATLAB}}==
<
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Student');
Line 2,164:
for I=0:1:RootXML.getElementsByTagName('Student').getLength-1
disp(RootXML.getElementsByTagName('Student').item(I).getAttributes.item(tag).getValue)
end</
{{out}}
Line 2,176:
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
XML/Input in Neko
Tectonics:
Line 2,205:
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:
=={{header|newLISP}}==
<
(set 'xml-input "<Students>
<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />
Line 2,240:
(if (= (length x) 6)
(println (last (sexp (chop x))))))
</syntaxhighlight>
Output:
Line 2,251:
=={{header|Nim}}==
<
let doc = newStringStream """<Students>
Line 2,264:
for i in doc.parseXml.findAll "Student":
echo i.attr "Name"</
Output:
<pre>April
Line 2,273:
=={{header|Objeck}}==
<
use XML;
Line 2,301:
}
}
</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:
Dave
Émily
- : unit = ()</
Another solution using the library [http://erratique.ch/software/xmlm xmlm]:
<
#load "xmlm.cmo"
open Xmlm
Line 2,356:
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:
);
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:
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:
DELETE OBJECT hxdoc.
MESSAGE cstudents VIEW-AS ALERT-BOX.</
'''Output:'''
Line 2,474:
=={{header|Oz}}==
<
[XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']}
Parser = {New XMLParser.parser init}
Line 2,505:
StudentNames = {Map Students GetStudentName}
in
{ForAll StudentNames System.showInfo}</
=={{header|Perl}}==
{{libheader|XML::Simple}}
<
use XML::Simple;
Line 2,522:
</Students>');
print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}});</
{{out}}
<pre>April
Line 2,531:
=={{header|Phix}}==
<!--<
<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>
Line 2,561:
<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>
<!--</
{{out}}
Note the last line (É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>
Line 2,575:
=={{header|PHP}}==
<
$data = '<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
Line 2,590:
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,621:
collect += ({ node->get_attributes()->Name });
});
write("%{%s\n%}", collect);</
Output:
Line 2,631:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
[xml]$xml = @'
<Students>
Line 2,648:
</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,701:
MessageRequester("Student Names", studentNames\s)
FreeXML(0)
EndIf </
Sample output:
<pre>
Line 2,712:
=={{header|Python}}==
<
doc = """<Students>
Line 2,727:
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,743:
</Students>'))
close(tc)
str</
[1] "<Students>"
[2] " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />"
Line 2,753:
[8] " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />"
[9] "</Students>"
<
xmltree <- xmlTreeParse(str)
Line 2,770:
#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,799:
(se-path*/list '(Student #:Name) students)
</syntaxhighlight>
=={{header|Raku}}==
Line 2,806:
{{libheader|XML}}
<syntaxhighlight lang="raku"
my $xml = from-xml '<Students>
Line 2,818:
</Students>';
say .<Name> for $xml.nodes.grep(/Student/)</
=={{header|Rascal}}==
<
public void getNames(loc a){
Line 2,828:
case element(_,"Student",[_*,attribute(_,"Name", x),_*]): println(x);
};
}</
Output:
<
April
Bob
Line 2,836:
Dave
Émily
ok</
=={{header|REBOL}}==
<
Title: "XML Reading"
URL: http://rosettacode.org/wiki/XML_Reading
Line 2,873:
print select student/2 "Name"
]
]</
Output:
Line 2,885:
=={{header|REXX}}==
===version 1===
<
g.=
g.1 = '<Students> '
Line 2,901:
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,914:
===version 2===
This REXX version handles more HTML tags for output.
<
g.=
g.1 = '<Students> '
Line 2,998:
$=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,013:
=={{header|Ruby}}==
{{libheader|REXML}}
<
include REXML
Line 3,026:
# using xpath
doc.each_element("*/Student") {|node| puts node.attributes["Name"]}</
=={{header|Run BASIC}}==
<
'XMLPARSER methods
Line 3,072:
print count;" ";#spy value$();" ->";#spy ATTRIBVALUE$(1)
next count</
=={{header|Rust}}==
Line 3,079:
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,115:
}
Ok(())
}</
{{out}}
Line 3,131:
This DOM can then be iterated in a convenient fashion.
<
const DOCUMENT: &str = r#"
Line 3,158:
Ok(())
}
</syntaxhighlight>
{{out}}
Line 3,173:
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,184:
</Students>
students \ "Student" \\ "@Name" foreach println</
=={{header|Sidef}}==
{{trans|Perl}}
<
var ref = %S'XML::Simple'.XMLin('<Students>
Line 3,200:
</Students>');
ref{:Student}.each { say _{:Name} };</
{{out}}
<pre>
Line 3,214:
Slate's XML Reader is still being developed at the time of this writing.
<
tree: (Xml SimpleParser newOn: '<Students>
Line 3,234:
Dave
Émily
Nil</
=={{header|Tcl}}==
Using {{libheader|tDOM}}
<
set tree [dom parse $xml]
set studentNodes [$tree getElementsByTagName Student] ;# or: set studentNodes [[$tree documentElement] childNodes]
Line 3,244:
foreach node $studentNodes {
puts [$node getAttribute Name]
}</
Using {{libheader|TclXML}}
<
set parser [xml::parser -elementstartcommand elem]
proc elem {name attlist args} {
Line 3,253:
}
}
$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,306:
}
}
}</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
MODE DATA
Line 3,331:
ENDLOOP
ENDCOMPILE
</syntaxhighlight>
Output:
<pre>
Line 3,346:
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,364:
@{NAME 12} @GENDER @YEAR-@MONTH-@DAY @PET_TYPE @PET_NAME
@ (end)
@(end)</
Sample run:
Line 3,377:
To obtain the output specified in this task, we can simply reduce the @(output) block to this:
<
@NAME
@(end)</
<pre>
Line 3,389:
=={{header|VBA}}==
<
Const strXml As String = "" & _
Line 3,416:
End If
Set myNodes = Nothing
End Sub</
{{out}}
<pre>April
Line 3,426:
=={{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,435:
Type_Block(#2, Cur_Pos)
Type_Newline
}</
Output:
Line 3,445:
=={{header|Visual Basic .NET}}==
<
<Student Name="April"/>
<Student Name="Bob"/>
Line 3,457:
For Each name In names
Console.WriteLine(name)
Next</
=={{header|Wren}}==
Line 3,463:
{{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
Line 3,496:
}
}
}</
{{out}}
Line 3,509:
{{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.
<
var xml = """
Line 3,524:
var doc = XDocument.parse(xml)
var names = doc.root.elements("Student").map { |el| el.attribute("Name").value }.toList
System.print(names.join("\n"))</
=={{header|XPL0}}==
<
string 0; \use zero-terminated strings
Line 3,571:
CrLf(0);
];
]</
{{out}}
Line 3,583:
=={{header|Yabasic}}==
<
data 32, 173, 189, 156, 207, 190, 221, 245, 249, 184, 166, 174, 170, 32, 169, 238
Line 3,650:
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,672:
});
students.println();</
{{out}}<pre>L("April","Bob","Chad","Dave","Émily")</pre>
|