Thursday, September 27, 2007

Parsing XML in Run BASIC

One of the important feature that a Web 2.0 language needs is an XML parser. Run BASIC now has one built in. The XMLPARSER statement parses an XML string and returns an XML accessor object with a bunch of handy built-in methods for making your way through an XML document.
Here is a simple example of what that sort of code looks like:

a$ = "<program name=""myprog"" author=""Carl Gundel""/>"
xmlparser #parser, a$
print #parser key$()
for x = 1 to #parser attribCount()
key$ = #parser attribKey$(x)
print key$; ", ";
print #parser attribValue$(x)
next x

This short program produces:

program
name, myprog
author, Carl Gundel

And here is a short program which will display the tag names and contents of an artibrarily nested XML document:

xmlparser #doc, s$
print #doc key$()
call displayElements #doc
end

sub displayElements #xmlDoc
count = #xmlDoc elementCount()
for x = 1 to count
#elem = #xmlDoc #element(x)
print "Key: "; #elem key$();
value$ = #elem value$()
if value$ <> "" then
print " Value: "; value$
end if
print
call displayElements #elem
next x
end sub