summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/xmllib.lua58
1 files changed, 43 insertions, 15 deletions
diff --git a/lib/xmllib.lua b/lib/xmllib.lua
index c3d6358..1ef0f33 100644
--- a/lib/xmllib.lua
+++ b/lib/xmllib.lua
@@ -1,16 +1,38 @@
+local xml_remplacements = {
+ { "&", "&" },
+ { "<", "&lt;" },
+ { ">", "&gt;" },
+}
+
+local attribute_replacements = {
+ { '"', '\\"' },
+}
+
+local function generic_escape(str, remplacements)
+ local _, r
+
+ for _, r in pairs(xml_replacements) do
+ str = string.gsub(str, r[1], r[2])
+ end
+end
+
local function xml_escape(str)
- return string.gsub(str, "&", "&amp;")
+ return generic_escape(str, xml_replacements)
+end
+
+local function attribute_replacements(str)
+ return generic_escape(str, attribute_replacements)
end
-local function process_comment(table, a)
+local function process_comment(xm, a)
return "<!-- " .. a .. " -->"
end
-local function process_tag(table, key, a)
- local middle, options, options_str, k, v, b
+local function process_tag(xm, key, a)
+ local middle, attrs, attrs_str, k, v, b
middle = ""
- options = {}
+ attrs = {}
if type(a) == "table" then
for k, v in ipairs(a) do
@@ -18,7 +40,7 @@ local function process_tag(table, key, a)
end
for k, v in pairs(a) do
if (type(k) == "string") then
- options[k] = string.gsub(v, '"', '\\"')
+ attrs[k] = attribute_replacements(xml_replacements(v))
end
end
elseif type(a) == "string" then
@@ -26,24 +48,24 @@ local function process_tag(table, key, a)
end
if middle ~= "" then
- options_str = ""
- for k, v in pairs(options) do
+ attrs_str = ""
+ for k, v in pairs(attrs) do
if (v == "") then
- options_str = " " .. options_str .. k
+ attrs_str = " " .. attrs_str .. k
else
- options_str = " " .. options_str .. k .. '="' .. v .. '"'
+ attrs_str = " " .. attrs_str .. k .. '="' .. v .. '"'
end
end
- return "<" .. key .. options_str .. ">" .. middle .. "</" .. key .. ">"
+ return "<" .. key .. attrs_str .. ">" .. middle .. "</" .. key .. ">"
else
return "<" .. key .. " />"
end
end
local xmlmarkup_metatable = {
- __index = function(table, key)
+ __index = function(xm, key)
local k = key
- return function(t, a) return process_tag(t, k, a) end
+ return function(xm, a) return process_tag(xm, k, a) end
end
}
@@ -57,11 +79,17 @@ function NewXmlMarkup()
return r
end
---[[
+
+--[[ example of use:
+
+-- result is:
+-- <html><head><title>Test</title></head><body bgcolor="#ffeedd">Normal test<br /><b>Bold test.</b><!-- Hi there... --></body></html>
+
xm = NewXmlMarkup()
-s = xm:html {
+s =
+xm:html {
xm:head {
xm:title "Test"
},