lua-users home
lua-l archive

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


Hello,

Here is a implementation of David Sklar's BadgerFish [1] convention for translating an XML document into a Lua table:

http://dev.alt.textdrive.com/browser/HTTP/XML.lua

1. Element names become table keys.

2. Text content of elements goes in the '$' key of a table.
   <alice>bob</alice>
   becomes
   { alice  = { [ '$' ] = 'bob' } }

3. Nested elements become nested tables.
   <alice><bob>charlie</bob><david>edgar</david></alice>
   becomes
{ alice = { bob = { [ '$' ] = 'charlie' }, david = { [ '$' ] = 'edgar' } } }

4. Multiple elements at the same level become list elements.
   <alice><bob>charlie</bob><bob>david</bob></alice>
   becomes
{ alice = { bob = { { [ '$' ] = 'charlie' }, { [ '$' ] = 'david' } } } }

5. Attributes go in keys whose names begin with '@'.
   <alice charlie="david">bob</alice>
   becomes
   { alice: { [ '$' ] = 'bob', [ '@charlie' ] = 'david' } }


Usage example:

local XML = require( 'XML' )
local aContent = io.open( 'atom.xml', 'rb' ):read( '*a' )
local anXML = XML( aContent )

print( anXML.feed[ '@xml:base' ] )
print( anXML.feed.title[ '$' ] )
print( anXML.feed.entry[ 1 ].id[ '$' ] )

for anIndex, anItem in ipairs( anXML.feed.entry ) do
    print( anIndex, anItem.title[ '$' ] )
end

Cheers,

PA.

[1] http://badgerfish.ning.com/