lua-users home
lua-l archive

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


I will try the penlight way. I will also need to create xml file from specific data struct or table, not sure if penlight has this capability.
Thank you very much for the info!
 
Jim
From: TNHarris <telliamed@whoopdedo.org>
To: lua-l@lists.lua.org
Sent: Wednesday, February 6, 2013 8:01 PM
Subject: Re: xml parsing problem

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
            end
          end
        end
        return nil
      end)
    end

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

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

[1] https://github.com/stevedonovan/Penlight/blob/master/docs/manual/06-
data.md#xml

--
tom <telliamed@whoopdedo.org>