mathml/luamml-xmlwriter.lua

47 lines
1.3 KiB
Lua
Raw Normal View History

2021-04-18 15:19:52 +02:00
-- FIXME: Not sure yet if this will be needed
local function escape_name(name)
return name
end
local escapes = {
['"'] = """,
['<'] = "&lt;",
['>'] = "&gt;",
['&'] = "&amp;",
}
local function escape_text(text)
2021-04-19 13:30:54 +02:00
return string.gsub(tostring(text), '("<>&)', escapes)
2021-04-18 15:19:52 +02:00
end
2021-04-19 13:30:54 +02:00
local function write_elem(tree, indent)
2021-04-18 15:19:52 +02:00
if not tree[0] then print('ERR', require'inspect'(tree)) end
local escaped_name = escape_name(assert(tree[0]))
local out = "<" .. escaped_name
2021-04-19 13:30:54 +02:00
if indent then out = indent .. out end
2021-04-18 15:19:52 +02:00
for attr, val in next, tree do if type(attr) == 'string' then
out = out .. ' ' .. escape_name(attr) .. '="' .. escape_text(val) .. '"'
end end
if not tree[1] then
return out .. '/>'
end
out = out .. '>'
2021-04-19 13:30:54 +02:00
local inner_indent = indent and indent .. ' '
2021-04-18 15:19:52 +02:00
for _, elem in ipairs(tree) do
if type(elem) == 'string' then
2021-04-19 13:30:54 +02:00
if inner_indent then
out = out .. inner_indent
end
2021-04-18 15:19:52 +02:00
out = out .. escape_text(elem)
else
2021-04-19 13:30:54 +02:00
out = out .. write_elem(elem, inner_indent)
2021-04-18 15:19:52 +02:00
end
end
2021-04-19 13:30:54 +02:00
if indent then out = out .. indent end
2021-04-18 15:19:52 +02:00
return out .. '</' .. escaped_name .. '>'
end
2021-04-23 02:58:07 +02:00
return function(element, indent, version)
return (version == '11' and '<?xml version="1.1"?>' or '') ..
write_elem(element, indent and '' or nil)
end