Jianw
2025-05-13 3b39fe3810c3ee2ec9ec97236c1769c5c85e062c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env lua
 
---Sample application to read a XML file and print it on the terminal.
--@author Manoel Campos da Silva Filho - http://manoelcampos.com
 
local xml2lua = require("xml2lua")
print("xml2lua v" .. xml2lua._VERSION.."\n")
 
--Uses a handler that converts the XML to a Lua table
local handler = require("xmlhandler.tree")
 
 
local xml = xml2lua.loadFile("people1.xml")
 
--Instantiates the XML parser
local parser = xml2lua.parser(handler)
parser:parse(xml)
 
--[[
By default, assumes the people table has just one person table.
Iterating over the people table we'll directly get the single person that it represents.
]]
local people = handler.root.people
 
--[[
If there is more than one person, then person is an array instead of a regular table.
This way, we need to iterate over the person array instead of the people table.
]]
if #people.person > 1 then
   people = people.person
end
 
--Manually prints the table (since the XML structure for this example is previously known)
for i, p in pairs(people) do
  print(i, "Name:", p.name, "City:", p.city, "Type:", p._attr.type)
end
 
--Recursivelly prints the table in an easy-to-ready format
--xml2lua.printable(handler.root)