-
Notifications
You must be signed in to change notification settings - Fork 75
/
xml2lua.lua
executable file
·286 lines (258 loc) · 7.87 KB
/
xml2lua.lua
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
--- @module Module providing a non-validating XML stream parser in Lua.
--
-- Features:
-- =========
--
-- * Tokenises well-formed XML (relatively robustly)
-- * Flexible handler based event API (see below)
-- * Parses all XML Infoset elements - ie.
-- - Tags
-- - Text
-- - Comments
-- - CDATA
-- - XML Decl
-- - Processing Instructions
-- - DOCTYPE declarations
-- * Provides limited well-formedness checking
-- (checks for basic syntax & balanced tags only)
-- * Flexible whitespace handling (selectable)
-- * Entity Handling (selectable)
--
-- Limitations:
-- ============
--
-- * Non-validating
-- * No charset handling
-- * No namespace support
-- * Shallow well-formedness checking only (fails
-- to detect most semantic errors)
--
-- API:
-- ====
--
-- The parser provides a partially object-oriented API with
-- functionality split into tokeniser and handler components.
--
-- The handler instance is passed to the tokeniser and receives
-- callbacks for each XML element processed (if a suitable handler
-- function is defined). The API is conceptually similar to the
-- SAX API but implemented differently.
--
-- XML data is passed to the parser instance through the 'parse'
-- method (Note: must be passed a single string currently)
--
-- License:
-- ========
--
-- This code is freely distributable under the terms of the [MIT license](LICENSE).
--
--
--@author Paul Chakravarti (paulc@passtheaardvark.com)
--@author Manoel Campos da Silva Filho
local xml2lua = { _VERSION = "1.6-1" }
local XmlParser = require("XmlParser")
---Recursivelly prints a table in an easy-to-ready format
--@param tb The table to be printed
--@param level the indentation level to start with
local function printableInternal(tb, level)
if tb == nil then
return
end
level = level or 1
local spaces = string.rep(' ', level*2)
for k,v in pairs(tb) do
if type(v) == "table" then
print(spaces .. k)
printableInternal(v, level+1)
else
print(spaces .. k..'='..v)
end
end
end
---Instantiates a XmlParser object to parse a XML string
--@param handler Handler module to be used to convert the XML string
--to another formats. See the available handlers at the handler directory.
-- Usually you get an instance to a handler module using, for instance:
-- local handler = require("xmlhandler/tree").
--@return a XmlParser object used to parse the XML
--@see XmlParser
function xml2lua.parser(handler)
if handler == xml2lua then
error("You must call xml2lua.parse(handler) instead of xml2lua:parse(handler)")
end
local options = {
--Indicates if whitespaces should be striped or not
stripWS = 1,
expandEntities = 1,
errorHandler = function(errMsg, pos)
error(string.format("%s [char=%d]\n", errMsg or "Parse Error", pos))
end
}
return XmlParser.new(handler, options)
end
---Recursivelly prints a table in an easy-to-ready format
--@param tb The table to be printed
function xml2lua.printable(tb)
printableInternal(tb)
end
---Handler to generate a string prepresentation of a table
--Convenience function for printHandler (Does not support recursive tables).
--@param t Table to be parsed
--@return a string representation of the table
function xml2lua.toString(t)
local sep = ''
local res = ''
if type(t) ~= 'table' then
return t
end
for k,v in pairs(t) do
if type(v) == 'table' then
v = xml2lua.toString(v)
end
res = res .. sep .. string.format("%s=%s", k, v)
sep = ','
end
res = '{'..res..'}'
return res
end
--- Loads an XML file from a specified path
-- @param xmlFilePath the path for the XML file to load
-- @return the XML loaded file content
function xml2lua.loadFile(xmlFilePath)
local f, e = io.open(xmlFilePath, "r")
if f then
--Gets the entire file content and stores into a string
local content = f:read("*a")
f:close()
return content
end
error(e)
end
---Gets an _attr element from a table that represents the attributes of an XML tag,
--and generates a XML String representing the attibutes to be inserted
--into the openning tag of the XML
--
--@param attrTable table from where the _attr field will be got
--@return a XML String representation of the tag attributes
local function attrToXml(attrTable)
local s = ""
attrTable = attrTable or {}
for k, v in pairs(attrTable) do
s = s .. " " .. k .. "=" .. '"' .. v .. '"'
end
return s
end
---Gets the first key of a given table
local function getSingleChild(tb)
local count = 0
for _ in pairs(tb) do
count = count + 1
end
if (count == 1) then
for k, _ in pairs(tb) do
return k
end
end
return nil
end
---Gets the first value of a given table
local function getFirstValue(tb)
if type(tb) == "table" then
for _, v in pairs(tb) do
return v
end
return nil
end
return tb
end
xml2lua.pretty = true
function xml2lua.getSpaces(level)
local spaces = ''
if (xml2lua.pretty) then
spaces = string.rep(' ', level * 2)
end
return spaces
end
function xml2lua.addTagValueAttr(tagName, tagValue, attrTable, level)
local attrStr = attrToXml(attrTable)
local spaces = xml2lua.getSpaces(level)
if (tagValue == '') then
table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '/>')
else
table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '>' .. tostring(tagValue) .. '</' .. tagName .. '>')
end
end
function xml2lua.startTag(tagName, attrTable, level)
local attrStr = attrToXml(attrTable)
local spaces = xml2lua.getSpaces(level)
if (tagName ~= nil) then
table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '>')
end
end
function xml2lua.endTag(tagName, level)
local spaces = xml2lua.getSpaces(level)
if (tagName ~= nil) then
table.insert(xml2lua.xmltb, spaces .. '</' .. tagName .. '>')
end
end
function xml2lua.isChildArray(obj)
for tag, _ in pairs(obj) do
if (type(tag) == 'number') then
return true
end
end
return false
end
function xml2lua.isTableEmpty(obj)
for k, _ in pairs(obj) do
if (k ~= '_attr') then
return false
end
end
return true
end
function xml2lua.parseTableToXml(obj, tagName, level)
if (tagName ~= '_attr') then
if (type(obj) == 'table') then
if (xml2lua.isChildArray(obj)) then
for _, value in pairs(obj) do
xml2lua.parseTableToXml(value, tagName, level)
end
elseif xml2lua.isTableEmpty(obj) then
xml2lua.addTagValueAttr(tagName, "", obj._attr, level)
else
xml2lua.startTag(tagName, obj._attr, level)
for tag, value in pairs(obj) do
xml2lua.parseTableToXml(value, tag, level + 1)
end
xml2lua.endTag(tagName, level)
end
else
xml2lua.addTagValueAttr(tagName, obj, nil, level)
end
end
end
---Converts a Lua table to a XML String representation.
--@param tb Table to be converted to XML
--@param tableName Name of the table variable given to this function,
-- to be used as the root tag. If a value is not provided
-- no root tag will be created.
--@param level Only used internally, when the function is called recursively to print indentation
--
--@return a String representing the table content in XML
function xml2lua.toXml(tb, tableName, level)
xml2lua.xmltb = {}
level = level or 0
local singleChild = getSingleChild(tb)
tableName = tableName or singleChild
if (singleChild) then
xml2lua.parseTableToXml(getFirstValue(tb), tableName, level)
else
xml2lua.parseTableToXml(tb, tableName, level)
end
if (xml2lua.pretty) then
return table.concat(xml2lua.xmltb, '\n')
end
return table.concat(xml2lua.xmltb)
end
return xml2lua