Advertisement
Hikooshi

xml.lua

Jul 9th, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. local xml = {}
  2.  
  3. ------------------------------------------------------------------------------------------------------------
  4.  
  5. function xml.parseargs(s)
  6. local arg = {}
  7. string.gsub(s, "([%-%w]+)=([\"'])(.-)%2", function (w, _, a)
  8. arg[w] = a
  9. end)
  10. return arg
  11. end
  12.  
  13. function xml.collect(s)
  14. local stack = {}
  15. local top = {}
  16. table.insert(stack, top)
  17. local ni,c,label,xarg, empty
  18. local i, j = 1, 1
  19. while true do
  20. ni,j,c,label,xarg, empty = string.find(s, "<(%/?)([%w:]+)(.-)(%/?)>", i)
  21. if not ni then break end
  22. local text = string.sub(s, i, ni-1)
  23. if not string.find(text, "^%s*$") then
  24. table.insert(top, text)
  25. end
  26. if empty == "/" then -- empty element tag
  27. table.insert(top, {label=label, xarg=xml.parseargs(xarg), empty=1})
  28. elseif c == "" then -- start tag
  29. top = {label=label, xarg=xml.parseargs(xarg)}
  30. table.insert(stack, top) -- new level
  31. else -- end tag
  32. local toclose = table.remove(stack) -- remove top
  33. top = stack[#stack]
  34. if #stack < 1 then
  35. error("nothing to close with "..label)
  36. end
  37. if toclose.label ~= label then
  38. error("trying to close "..toclose.label.." with "..label)
  39. end
  40. table.insert(top, toclose)
  41. end
  42. i = j+1
  43. end
  44. local text = string.sub(s, i)
  45. if not string.find(text, "^%s*$") then
  46. table.insert(stack[#stack], text)
  47. end
  48. if #stack > 1 then
  49. error("unclosed "..stack[#stack].label)
  50. end
  51. return stack[1]
  52. end
  53.  
  54. ------------------------------------------------------------------------------------------------------------
  55.  
  56. return xml
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement