Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
26 changes: 21 additions & 5 deletions xml2lua.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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, "<", "&lt;")
value = string.gsub(value, ">", "&gt;")
value = string.gsub(value, "'", "&apos;")
value = string.gsub(value, "\"", "&quot;")
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
Expand All @@ -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
Expand Down Expand Up @@ -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) .. '</' .. tagName .. '>')
table.insert(xml2lua.xmltb, spaces .. '<' .. tagName .. attrStr .. '>' .. escapeXmlChar(tostring(tagValue)) .. '</' .. tagName .. '>')
end
end

Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down