@@ -179,23 +179,29 @@ end
179179function xml2lua .toXml (tb , tableName , level )
180180 level = level or 1
181181 local spaces = string.rep (' ' , level * 2 )
182- tableName = tableName or " "
182+ tableName = tableName or ' '
183183 local xmltb = (tableName ~= ' ' and level == 1 ) and {' <' .. tableName .. ' >' } or {}
184184
185185 for k , v in pairs (tb ) do
186- if type (v ) == " table" then
187- -- If the keys of the table are a number, it represents an array
188- if type (k ) == " number" then
186+ if type (v ) == ' table' then
187+ -- If the key is a number, the given table is an array and the value is an element inside that array.
188+ -- In this case, the name of the array is used as tag name for each element.
189+ -- So, we are parsing an array of objects, not an array of primitives.
190+ if type (k ) == ' number' then
189191 local attrs = attrToXml (v ._attr )
190192 v ._attr = nil
191193 table.insert (xmltb ,
192194 spaces .. ' <' .. tableName .. attrs .. ' >\n ' .. xml2lua .toXml (v , tableName , level + 1 )..
193195 ' \n ' .. spaces .. ' </' .. tableName .. ' >' )
194196 else
195197 level = level + 1
196- if type (getFirstKey (v )) == " number" then
198+ -- If the type of the first key of the value inside the table
199+ -- is a number, it means we have a HashMap-like structcture,
200+ -- in this case with keys as strings and values as arrays.
201+ if type (getFirstKey (v )) == ' number' then
197202 table.insert (xmltb , xml2lua .toXml (v , k , level ))
198203 else
204+ -- Otherwise, the "HashMap" values are objects
199205 local attrs = attrToXml (v ._attr )
200206 v ._attr = nil
201207 table.insert (xmltb ,
@@ -204,9 +210,10 @@ function xml2lua.toXml(tb, tableName, level)
204210 end
205211 end
206212 else
213+ -- When values are primitives:
207214 -- If the type of the key is number, the value is an element from an array.
208- -- In this case, uses the array name (the name of the array) as the tag name.
209- if type (k ) == " number" then
215+ -- In this case, uses the array name as the tag name.
216+ if type (k ) == ' number' then
210217 k = tableName
211218 end
212219 table.insert (xmltb , spaces .. ' <' .. k .. ' >' .. tostring (v ).. ' </' .. k .. ' >' )
@@ -217,7 +224,7 @@ function xml2lua.toXml(tb, tableName, level)
217224 table.insert (xmltb , ' </' .. tableName .. ' >\n ' )
218225 end
219226
220- return table.concat (xmltb , " \n " )
227+ return table.concat (xmltb , ' \n ' )
221228end
222229
223230return xml2lua
0 commit comments