lua-users home
lua-l archive

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

On Wednesday, February 06, 2013 09:56:20 AM Jim zhang wrote:
> I try to use lxp.lom to parse xml file, but it gives empty table. Here is
> the code: -- setup XML parser
> local lom = require "lxp.lom"
> When I try to print out tbl[1][1]:
> io.write(tostring(tbl[1][cusomer_cnt]))
> the print out result is:  nil

As Thomas Buergel pointed out, the LOM includes text nodes. Penlight[1] makes 
working with XML more convenient. But if you just want some DOM-like methods, 
it's easy enough to roll your own.

    function GetElementsByTagName(root,name)
      local yield = coroutine.yield
      local descend = {root}
      return coroutine.wrap(function()
        for _,elem in ipairs(descend) do
          for _,child in ipairs(elem) do
            if type(child)=='table' then
              if child.tag==name then yield(child) end
              if #child > 0 then descend[#descend+1] = child end
        return nil

    for customer in GetElementsByTagName(lom.parse(xml), 'Customer') do
      print("Company:",GetFirstChildByTagName(customer, 'CompanyName')[1])

GetFirstChildByTagName is left as an exercise for the reader. And you most 
likely want to use assert to catch errors.


tom <>