lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Pedro Maia wrote:
> I'm looking for a script that converts XML tags in lua tables.
> Does anyone knows where I can find it?

I adapted this one from a version made by Roberto. It works pretty
well.

Regards,
Mark

-- 
|\/|ark Stroetzel Glasberg
mark@tecgraf.puc-rio.br

Computer Engineer

Tecgraf/PUC-Rio
Rua Marques de Sao Vicente, 225 - Predio ITS
Gavea - Rio de Janeiro - RJ cep. 22453-900
URL:  http://www.tecgraf.puc-rio.br/~mark
Tel:  55 21 2512-5984 ext. 116
Fax:  55 21 2259-2232
$debug

XML = {}

-- auxiliar function to parse tag attributes
function XML:parse_args(s)
  local arg = {}
  gsub(s, "([%w_]+)%s*=%s*([\"'])(.-)%2", function (w, _, a)
    %arg[w] = a
  end)
  return arg
end

-- string "s" is a string with XML marks. This function parses the string
-- and returns the resulting tree.
function XML:parse(s)
  local stack = {n=0}
  local top = {n=0}
  tinsert(stack, top)
  local i = 1
  local ni,j,c,label,args, empty = strfind(s, "<(%/?)([%w_]+)(.-)(%/?)>")
  while ni do
    local text = strsub(s, i, ni-1)
    if not strfind(text, "^%s*$") then
      tinsert(top, text)
    end
    if empty == "/" then  -- empty element tag
      tinsert(top, {n=0, label=label, args=self:parse_args(args), empty=1})
    elseif c == "" then   -- start tag
      top = {n=0, label=label, args=self:parse_args(args)}
      tinsert(stack, top)   -- new level
    else  -- end tag
      local toclose = tremove(stack)  -- remove top
      top = stack[stack.n]
      if stack.n < 1 then
        printError("Tag <"..label.."> sem fechamento.")
      end
      if toclose.label ~= label then
        printError("Tag <"..toclose.label.."> fechado com <"..label..">.")
      end
      tinsert(top, toclose)
    end 
    i = j+1
    ni,j,c,label,args, empty = strfind(s, "<(%/?)([%w_]+)(.-)(%/?)>", j)
  end
  local text = strsub(s, i)
  if not strfind(text, "^%s*$") then
    tinsert(stack[stack.n], text)
  end
  return stack[1]
end