xml2lua is an XML parser written entirely in Lua which doesn’t depend on any external C/C++ library. It works for Lua 5.1 to 5.3 and enables:
-
parsing an XML string into a Lua Table;
-
converting a Lua Table to an XML string.
The original parser was written by Paul Chakravarti and is available on LuaUsers.
1. Installation
1.1. From LuaRocks repository
The best way to download the module is using LuaRocks at the command line:
2. How to use
2.1. Parsing an XML String into a Lua Table
A simplified example which parses an XML directly from a string is presented below. There are some caveats to deal with when an XML has just one tag. Check the example1.lua for details.
local xml2lua = require("xml2lua") --Uses a handler that converts the XML to a Lua table local handler = require("xmlhandler.tree") local xml = [[ <people> <person type="natural"> <name>Manoel</name> <city>Palmas-TO</city> </person> <person type="legal"> <name>University of BrasÃlia</name> <city>BrasÃlia-DF</city> </person> </people> ]] --Instantiates the XML parser local parser = xml2lua.parser(handler) parser:parse(xml) --Manually prints the table (since the XML structure for this example is previously known) for i, p in pairs(handler.root.people.person) do print(i, "Name:", p.name, "City:", p.city, "Type:", p._attr.type) end
2.2. Converting a Lua Table to an XML String
local xml2lua = require("xml2lua") local people = { person = { {name="Manoel", city="Palmas-TO", _attr={ type='natural' } }, {name="Breno", city="Palmas-TO", _attr={ type='legal' } } } } print("People Table\n") xml2lua.printable(people) print() print("XML Representation\n") print(xml2lua.toXml(people, "people"))
3. Command line tool
You can use a command line tool to try parsing XML files.
Execute lua testxml.lua -help on the terminal for more details.
-
Manoel Campos da Silva Filho http://about.me/manoelcampos
-
Paul Chakravarti paulc@passtheaardvark.com
