Guest User

Untitled

a guest
Jan 20th, 2018
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. -- luatbl2xml
  2. -- A very simple converter from lua tables to xml
  3.  
  4. function luatbl2xml (tbl, tb)
  5. local tab = tb or 0;
  6. local eltname = '';
  7. local attrs = ''
  8.  
  9. -- Get the tagname and attributes
  10. for k, v in pairs (tbl) do
  11. if type (k) == "number" then
  12. if k == 1 then
  13. eltname = v;
  14. end
  15. elseif type (k) == "string" then
  16. attrs = attrs .. ' ' .. k .. '="' .. v .. '"'
  17. end
  18. end
  19.  
  20. -- Go recursively into children
  21. local children = ''
  22. for k, v in pairs (tbl) do
  23. if k ~= 1 and type(v) == 'table' then
  24. children = children .. luatbl2xml (v, tab+2) .. '\n';
  25. end
  26. end
  27.  
  28. if children ~= '' then
  29. local begin_elt = "<" .. eltname .. attrs .. ">\n";
  30. for i=1, tab do
  31. begin_elt = ' ' .. begin_elt
  32. end
  33.  
  34. local end_elt = "</" .. eltname .. ">"
  35. for i=1, tab do
  36. end_elt = ' ' .. end_elt
  37. end
  38.  
  39. return begin_elt .. children .. end_elt
  40.  
  41. else
  42. local begin_end_elt = "<" .. eltname .. attrs .. "/>";
  43.  
  44. for i=1, tab do
  45. begin_end_elt = ' ' .. begin_end_elt
  46. end
  47.  
  48. return begin_end_elt
  49. end
  50. end
  51.  
  52. doc =
  53. {"ncl", id="myid",
  54. {"body", id="body",
  55. {"port", component="m1"},
  56. {"media", id="m1", src="video.mp4"},
  57. {"link", id="l1",
  58. {"bind", role="onEnd", component="m1"},
  59. {"bind", role="start", component="m1"}
  60. }
  61. }
  62. }
  63.  
  64. print (luatbl2xml (doc))
Add Comment
Please, Sign In to add comment