local xml_remplacements = { { "&", "&" }, { "<", "<" }, { ">", ">" }, } 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 generic_escape(str, xml_replacements) end local function attribute_replacements(str) return generic_escape(str, attribute_replacements) end local function process_comment(xm, a) return "" end local function process_tag(xm, key, a) local middle, attrs, attrs_str, k, v, b middle = "" attrs = {} if type(a) == "table" then for k, v in ipairs(a) do middle = middle .. v end for k, v in pairs(a) do if (type(k) == "string") then attrs[k] = attribute_replacements(xml_replacements(v)) end end elseif type(a) == "string" then middle = xml_escape(a) end if middle ~= "" then attrs_str = "" for k, v in pairs(attrs) do if (v == "") then attrs_str = " " .. attrs_str .. k else attrs_str = " " .. attrs_str .. k .. '="' .. v .. '"' end end return "<" .. key .. attrs_str .. ">" .. middle .. "" else return "<" .. key .. " />" end end local xmlmarkup_metatable = { __index = function(xm, key) local k = key return function(xm, a) return process_tag(xm, k, a) end end } function NewXmlMarkup() local r = { comment = process_comment, } setmetatable(r, xmlmarkup_metatable) return r end --[[ example of use: -- result is: -- TestNormal test
Bold test. xm = NewXmlMarkup() s = xm:html { xm:head { xm:title "Test" }, xm:body { bgcolor = "#ffeedd", "Normal test", xm:br(), xm:b "Bold test.", xm:comment "Hi there...", } } print(s) ]]--