src/lxp/lom.lua

changeset 10
e981a82571cf
parent 0
24d141cb2d1e
child 36
4a61f00ee916
equal deleted inserted replaced
9:5dfed844930e 10:e981a82571cf
1 -- See Copyright Notice in license.html 1 -- See Copyright Notice in license.html
2 -- $Id: lom.lua,v 1.6 2005/06/09 19:18:40 tuler Exp $ 2 -- $Id: lom.lua,v 1.6 2005/06/09 19:18:40 tuler Exp $
3 3
4 require "lxp" 4 local lxp = require "lxp"
5 5
6 local tinsert, tremove, getn = table.insert, table.remove, table.getn 6 local tinsert, tremove = table.insert, table.remove
7 local assert, type, print = assert, type, print 7 local assert, type, print = assert, type, print
8 local lxp = lxp
9 8
10 module ("lxp.lom")
11 9
12 local function starttag (p, tag, attr) 10 local function starttag (p, tag, attr)
13 local stack = p:getcallbacks().stack 11 local stack = p:getcallbacks().stack
14 local newelement = {tag = tag, attr = attr} 12 local newelement = {tag = tag, attr = attr}
15 tinsert(stack, newelement) 13 tinsert(stack, newelement)
17 15
18 local function endtag (p, tag) 16 local function endtag (p, tag)
19 local stack = p:getcallbacks().stack 17 local stack = p:getcallbacks().stack
20 local element = tremove(stack) 18 local element = tremove(stack)
21 assert(element.tag == tag) 19 assert(element.tag == tag)
22 local level = getn(stack) 20 local level = #stack
23 tinsert(stack[level], element) 21 tinsert(stack[level], element)
24 end 22 end
25 23
26 local function text (p, txt) 24 local function text (p, txt)
27 local stack = p:getcallbacks().stack 25 local stack = p:getcallbacks().stack
28 local element = stack[getn(stack)] 26 local element = stack[#stack]
29 local n = getn(element) 27 local n = #element
30 if type(element[n]) == "string" then 28 if type(element[n]) == "string" then
31 element[n] = element[n] .. txt 29 element[n] = element[n] .. txt
32 else 30 else
33 tinsert(element, txt) 31 tinsert(element, txt)
34 end 32 end
35 end 33 end
36 34
37 function parse (o) 35 local function parse (o)
38 local c = { StartElement = starttag, 36 local c = { StartElement = starttag,
39 EndElement = endtag, 37 EndElement = endtag,
40 CharacterData = text, 38 CharacterData = text,
41 _nonstrict = true, 39 _nonstrict = true,
42 stack = {{}} 40 stack = {{}}
45 local status, err 43 local status, err
46 if type(o) == "string" then 44 if type(o) == "string" then
47 status, err = p:parse(o) 45 status, err = p:parse(o)
48 if not status then return nil, err end 46 if not status then return nil, err end
49 else 47 else
50 for l in o do 48 for l in pairs(o) do
51 status, err = p:parse(l) 49 status, err = p:parse(l)
52 if not status then return nil, err end 50 if not status then return nil, err end
53 end 51 end
54 end 52 end
55 status, err = p:parse() 53 status, err = p:parse()
56 if not status then return nil, err end 54 if not status then return nil, err end
57 p:close() 55 p:close()
58 return c.stack[1][1] 56 return c.stack[1][1]
59 end 57 end
60 58
59 return { parse = parse }

mercurial