-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlxp_table.lua
More file actions
54 lines (52 loc) · 1.5 KB
/
lxp_table.lua
File metadata and controls
54 lines (52 loc) · 1.5 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
local lxp = require "lxp" -- http://www.keplerproject.org/luaexpat
local lxp_table = {}
-- Parse an XML document and return corresponding Lua tables.
-- f - a file object to read from
function lxp_table.parse_xml(f)
local root = {}
local node = root
local parser = lxp.new(
{
Comment = function(parser, string)
table.insert(node, {name="#comment", value=string})
end,
StartElement = function(parser, element_name, attributes)
local new_node =
{
name = element_name,
attr = attributes or {},
parent = node
}
table.insert(node, new_node)
node = new_node
end,
EndElement = function(parser, element_name)
assert(node.name == element_name, "Mismatched tags")
node = node.parent
end,
Default = function(parser, string)
-- Omit whitespace
if string:find("[^ \t\n]") then
table.insert(node, string)
end
end,
}
)
-- Read the whole input file
while true do
local buf, err = f:read(1024)
if not buf then
if err then
error(err)
end
break
end
local status, msg, line, col = parser:parse(buf)
if not status then
error(string.format("<xml>:%d:%d: %s", line, col, msg))
end
end
parser:close()
return root
end
return lxp_table