|
| 1 | +local XMLNode = { |
| 2 | + new = function(tag) |
| 3 | + return { |
| 4 | + tag = tag, |
| 5 | + value = nil, |
| 6 | + attributes = {}, |
| 7 | + children = {}, |
| 8 | + |
| 9 | + addChild = function(self, child) |
| 10 | + table.insert(self.children, child) |
| 11 | + end, |
| 12 | + |
| 13 | + addAttribute = function(self, tag, value) |
| 14 | + self.attributes[tag] = value |
| 15 | + end |
| 16 | + } |
| 17 | + end |
| 18 | +} |
| 19 | + |
| 20 | +local parseAttributes = function(node, s) |
| 21 | + -- Parse "" style string attributes |
| 22 | + local _, _ = string.gsub(s, "(%w+)=([\"'])(.-)%2", function(attribute, _, value) |
| 23 | + node:addAttribute(attribute, "\"" .. value .. "\"") |
| 24 | + end) |
| 25 | + -- Parse {} style computed attributes |
| 26 | + local _, _ = string.gsub(s, "(%w+)={(.-)}", function(attribute, expression) |
| 27 | + node:addAttribute(attribute, expression) |
| 28 | + end) |
| 29 | +end |
| 30 | + |
| 31 | +local XMLParser = { |
| 32 | + parseText = function(xmlText) |
| 33 | + local stack = {} |
| 34 | + local top = XMLNode.new() |
| 35 | + table.insert(stack, top) |
| 36 | + local ni, c, label, xarg, empty |
| 37 | + local i, j = 1, 1 |
| 38 | + while true do |
| 39 | + ni, j, c, label, xarg, empty = string.find(xmlText, "<(%/?)([%w_:]+)(.-)(%/?)>", i) |
| 40 | + if not ni then break end |
| 41 | + local text = string.sub(xmlText, i, ni - 1); |
| 42 | + if not string.find(text, "^%s*$") then |
| 43 | + local lVal = (top.value or "") .. text |
| 44 | + stack[#stack].value = lVal |
| 45 | + end |
| 46 | + if empty == "/" then -- empty element tag |
| 47 | + local lNode = XMLNode.new(label) |
| 48 | + parseAttributes(lNode, xarg) |
| 49 | + top:addChild(lNode) |
| 50 | + elseif c == "" then -- start tag |
| 51 | + local lNode = XMLNode.new(label) |
| 52 | + parseAttributes(lNode, xarg) |
| 53 | + table.insert(stack, lNode) |
| 54 | + top = lNode |
| 55 | + else -- end tag |
| 56 | + local toclose = table.remove(stack) -- remove top |
| 57 | + |
| 58 | + top = stack[#stack] |
| 59 | + if #stack < 1 then |
| 60 | + error("XMLParser: nothing to close with " .. label) |
| 61 | + end |
| 62 | + if toclose.tag ~= label then |
| 63 | + error("XMLParser: trying to close " .. toclose.tag .. " with " .. label) |
| 64 | + end |
| 65 | + top:addChild(toclose) |
| 66 | + end |
| 67 | + i = j + 1 |
| 68 | + end |
| 69 | + local text = string.sub(xmlText, i); |
| 70 | + if #stack > 1 then |
| 71 | + error("XMLParser: unclosed " .. stack[#stack].tag) |
| 72 | + end |
| 73 | + return top |
| 74 | + end |
| 75 | +} |
| 76 | + |
| 77 | +return XMLParser |
0 commit comments