Comparison

util/xml.lua @ 5213:cc487921746b

util.xml: Initial commit; exposes parse(), which is now the canonical way to convert a string to a stanza.
author Waqas Hussain <waqas20@gmail.com>
date Mon, 03 Dec 2012 05:32:51 +0500
child 5223:76e4651142e1
comparison
equal deleted inserted replaced
5211:80635a6cb126 5213:cc487921746b
1
2 local st = require "util.stanza";
3 local lxp = require "lxp";
4
5 module("template")
6
7 local parse_xml = (function()
8 local ns_prefixes = {
9 ["http://www.w3.org/XML/1998/namespace"] = "xml";
10 };
11 local ns_separator = "\1";
12 local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$";
13 return function(xml)
14 local handler = {};
15 local stanza = st.stanza("root");
16 function handler:StartElement(tagname, attr)
17 local curr_ns,name = tagname:match(ns_pattern);
18 if name == "" then
19 curr_ns, name = "", curr_ns;
20 end
21 if curr_ns ~= "" then
22 attr.xmlns = curr_ns;
23 end
24 for i=1,#attr do
25 local k = attr[i];
26 attr[i] = nil;
27 local ns, nm = k:match(ns_pattern);
28 if nm ~= "" then
29 ns = ns_prefixes[ns];
30 if ns then
31 attr[ns..":"..nm] = attr[k];
32 attr[k] = nil;
33 end
34 end
35 end
36 stanza:tag(name, attr);
37 end
38 function handler:CharacterData(data)
39 stanza:text(data);
40 end
41 function handler:EndElement(tagname)
42 stanza:up();
43 end
44 local parser = lxp.new(handler, "\1");
45 local ok, err, line, col = parser:parse(xml);
46 if ok then ok, err, line, col = parser:parse(); end
47 --parser:close();
48 if ok then
49 return stanza.tags[1];
50 else
51 return ok, err.." (line "..line..", col "..col..")";
52 end
53 end;
54 end)();
55
56 parse = parse_xml;
57 return _M;