As mentioned in my last posting, I have been developing a simple XML parser for use with the Lua programming languge. It will most likely be a very basic parser, that is not one on terms with more advanced parsers.
So far I have implemented 2 basic functions for my parser:
- Loading XML documents
- Parsing short tags (e.g. Something like
<tag>value</tag>
)
To include the functionality of the parser (which is a Lua module) into a new Lua program, I include the line:
xml = require "xmlparser"
This gives the program access to the two functions (I have so far) provided by my parser.
These are:
xml.load(file as str)
xml.stag(xml as str, tag as str [, occur as int])
I have written this simple program to test my parser as it stands so far:
--------------------------------------------------
-- Example program using XML Parser
-- Copyright (c) 2007 Sam Saint-Pettersen
-- Released under the GNU General Public License
-- http://creativecommons.org/licenses/GPL/2.0/
--------------------------------------------------
-- include xmlparser module
xml = require "xmlparser"
-- load xml file
file = xml.load("employees.xml")
-- display name
print("Name: " .. xml.stag(file, "last") .. ", " ..
xml.stag(file, "first")) -- < this should be on above line
-- display position
print("Position: " .. xml.stag(file, "position"))
-- display e-mail addresss
print("E-mail: " .. xml.stag(file, "email"))
-- display home page
print("Home page: " .. xml.stag(file, "homepage"))
Below is my test XML file:
<employees>
<employee>
<first>Phoenix</first>
<last>Lightfoot</last>
<position>Lead Programmer</position>
<email>p.lightfoot@pathetecsys.com</email>
<homepage>http://www.pathetecsys.com/~lightfoot</homepage>
<telephone type="office">001 222 222</telephone>
<telephone type="mobile">777 222 333</telephone>
</employee>
<employee>
<first>Hugo</first>
<last>Jacob-Jones</last>
<position>Chief Executive Officer</position>
<email>h.jacobjones@pathetecsys.com</email>
<homepage>http://www.pathetecsys.com/~jacobjones</homepage>
<telephone type="office">001 222 200</telephone>
<telephone type="mobile">577 242 321</telephone>
</employee>
</employees>
Here is the console output from running my test program under the Lua interpreter:
Name: Lightfoot, Phoenix
Position: Lead Programmer
E-mail: p.lightfoot@pathetecsys.com
Home page: http://www.pathetecsys.com/~lightfoot
So far, so good. :)
I have yet to add the capability to specify an occurrence of a tag, based on its index and functions for parsing tags which contain attributes such as
<tag attribute="value">anothervalue</tag>
I should have that done soon enough.
Featured image courtesy of lambdageek (CC-BY-NC)