]> git.sesse.net Git - vlc/blob - share/lua/modules/simplexml.lua
Add a simplexml lua module to parse an xml into a table.
[vlc] / share / lua / modules / simplexml.lua
1 --[==========================================================================[
2  simplexml.lua: Lua simple xml parser wrapper
3 --[==========================================================================[
4  Copyright (C) 2010 Antoine Cellerier
5  $Id$
6
7  Authors: Antoine Cellerier <dionoea at videolan dot org>
8
9  This program is free software; you can redistribute it and/or modify
10  it under the terms of the GNU General Public License as published by
11  the Free Software Foundation; either version 2 of the License, or
12  (at your option) any later version.
13
14  This program is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  GNU General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with this program; if not, write to the Free Software
21  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 --]==========================================================================]
23
24 module("simplexml",package.seeall)
25
26 --[[ Returns the xml tree structure
27 --   Each node is of one of the following types:
28 --     { name (string), attributes (key->value map), children (node array) }
29 --     text content (string)
30 --]]
31
32 local function parsexml(stream)
33     local xml = vlc.xml()
34     local reader = xml:create_reader(stream)
35
36     local tree
37     local parents = {}
38     while reader:read() > 0 do
39         local nodetype = reader:node_type()
40         if nodetype == 'startelem' then
41             local name = reader:name()
42             local node = { name: '', attributes: {}, children: {} }
43             node.name = name
44             while reader:NextAttr() == 0 do
45                 node.attributes[reader:Name()] = reader:Value()
46             end
47             if tree then
48                 tree.children[#tree.children] = node
49                 parents[#parents] = tree
50                 tree = node
51             end
52         elseif nodetype == 'endelem' then
53             tree = parents[#parents-1]
54         elseif nodetype == 'text' then
55             node.children[#node.children] = reader:Value()
56         end
57     end
58
59     return tree
60 end
61
62 function parse_url(url)
63     return parsexml(vlc.stream(url))
64 end
65
66 function parse_string(str)
67     return parsexml(vlc.memory_stream(str))
68 end