diff --git a/.gitignore b/.gitignore index 156ecc0..f648248 100755 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,15 @@ *.rock -test.lua -teste.lua #IntelliJ IDEA Files .idea *.iml +#VS Code files +launch.json + #macOS .DS_Store + +#Debugging files +debugger.lua +test.lua diff --git a/xml2lua.lua b/xml2lua.lua index 813cf1e..71b98d0 100755 --- a/xml2lua.lua +++ b/xml2lua.lua @@ -140,6 +140,18 @@ function xml2lua.loadFile(xmlFilePath) error(e) end +---Checks the value for forbidden characters and escapes them +--@param value string for checking and correcting +--@return a XML-compliant string +local function escapeXmlChar(value) + value = string.gsub(value, "&", "&") + value = string.gsub(value, "<", "<") + value = string.gsub(value, ">", ">") + value = string.gsub(value, "'", "'") + value = string.gsub(value, "\"", """) + return value +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 @@ -151,7 +163,7 @@ local function attrToXml(attrTable) attrTable = attrTable or {} for k, v in pairs(attrTable) do - s = s .. " " .. k .. "=" .. '"' .. v .. '"' + s = s .. " " .. k .. "=" .. '"' .. escapeXmlChar(v) .. '"' end return s end @@ -198,7 +210,7 @@ function xml2lua.addTagValueAttr(tagName, tagValue, attrTable, level) if (tagValue == '') then table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '/>') else - table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '>' .. tostring(tagValue) .. '') + table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '>' .. escapeXmlChar(tostring(tagValue)) .. '') end end @@ -237,7 +249,7 @@ end function xml2lua.parseTableToXml(obj, tagName, level) if (tagName ~= '_attr') then - if (type(obj) == 'table') then + if (type(obj) == 'table' and (#obj ~= 1 or type(obj[1]) == 'table')) then if (xml2lua.isChildArray(obj)) then for _, value in pairs(obj) do xml2lua.parseTableToXml(value, tagName, level) @@ -252,10 +264,14 @@ function xml2lua.parseTableToXml(obj, tagName, level) xml2lua.endTag(tagName, level) end else - xml2lua.addTagValueAttr(tagName, obj, nil, level) + if type(obj) == 'table' then + xml2lua.addTagValueAttr(tagName, obj[1], obj._attr, level) + else + xml2lua.addTagValueAttr(tagName, obj, nil, level) + end end end - end +end ---Converts a Lua table to a XML String representation. --@param tb Table to be converted to XML