Stary2001

xml

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