@@ -138,4 +138,76 @@ function xml2lua.loadFile(xmlFilePath)
138138 error (e )
139139end
140140
141+ --- Gets an _attr element from a table that represents the attributes of an XML tag,
142+ -- and generates a XML String representing the attibutes to be inserted
143+ -- into the openning tag of the XML
144+ --
145+ -- @param attrTable table from where the _attr field will be got
146+ -- @return a XML String representation of the tag attributes
147+ local function attrToXml (attrTable )
148+ local s = " "
149+ local attrTable = attrTable or {}
150+
151+ for k , v in pairs (attrTable ) do
152+ s = s .. " " .. k .. " =" .. ' "' .. v .. ' "'
153+ end
154+ return s
155+ end
156+
157+ --- Gets the first key of a given table
158+ local function getFirstKey (tb )
159+ if type (tb ) == " table" then
160+ for k , v in pairs (tb ) do
161+ return k
162+ end
163+ return nil
164+ end
165+
166+ return tb
167+ end
168+
169+ --- Converts a Lua table to a XML String representation.
170+ -- @param tb Table to be converted to XML
171+ -- @param tableName Name of the table variable given to this function,
172+ -- to be used as the root tag.
173+ -- @param level Only used internally, when the function is called recursively to print indentation
174+ --
175+ -- @return a String representing the table content in XML
176+ function xml2lua .toXml (tb , tableName , level )
177+ local level = level or 0
178+ local firstLevel = level
179+ local spaces = string.rep (' ' , level * 2 )
180+ local xmltb = level == 0 and {' <' .. tableName .. ' >' } or {}
181+
182+ for k , v in pairs (tb ) do
183+ if type (v ) == " table" then
184+ -- If the keys of the table are a number, it represents an array
185+ if type (k ) == " number" then
186+ local attrs = attrToXml (v ._attr )
187+ v ._attr = nil
188+ table.insert (xmltb ,
189+ spaces .. ' <' .. tableName .. attrs .. ' >\n ' .. xml2lua .toXml (v , tableName , level + 1 )..
190+ ' \n ' .. spaces .. ' </' .. tableName .. ' >' )
191+ else
192+ level = level + 1
193+ if type (getFirstKey (v )) == " number" then
194+ table.insert (xmltb , spaces .. xml2lua .toXml (v , k , level ))
195+ else
196+ table.insert (
197+ xmltb ,
198+ spaces .. ' <' .. k .. ' >\n ' .. xml2lua .toXml (v , level + 1 )..
199+ ' \n ' .. spaces .. ' </' .. k .. ' >' )
200+ end
201+ end
202+ else
203+ table.insert (xmltb , spaces .. ' <' .. k .. ' >' .. tostring (v ).. ' </' .. k .. ' >' )
204+ end
205+ end
206+
207+ if firstLevel == 0 then
208+ table.insert (xmltb , ' </' .. tableName .. ' >\n ' )
209+ end
210+ return table.concat (xmltb , " \n " )
211+ end
212+
141213return xml2lua
0 commit comments