Get a deeper understanding of
Here's an important way to think about the results of E4X:
For the most part, the results are an
XMLList which is a fancy array which can contain items such as
XMLNodes and other XML types. You access this array to get at the main node types. As an example:
The following will search from the top of the xml document, looking for
book elements (returning an
XMLList result), then searching that list for
title elements (returning an
XMLList result). The list length can be checked to see if anything matches.
local results = xml.book.title -- returns an XMLList local count = xml.book.title:length() -- how many results -- count = results:length() -- same
This next example shows us retrieving a specfic result node from the list:
local title_node = xml.book.title -- we index `XMLList` to get at data, here an XMLNode print( title_node:toString() ) for i, title_node in xml.book.title:nodes() do print( i, title_node:toString() ) end
Searching via Dot Traversal
The great thing about E4X is that the simple dot-traversal syntax is essentially doing searches through the XML document grabbing results as it goes.
xml.book -- searches all children of the XML root for `book` elements. xml.book.author -- searches all children of each `book` result for `title` elements and returns those results, and so on. xml.book.author -- only searches the first `book` element for any children `author` elements.
Same API for XMLList and XMLNode
For the most part,
XMLNodes share the same API. If a method is called on an
XMLNode then it returns data for just that node. However, if the method is called on an
XMLList, the list will loop through all of its result nodes and call the method on those, then return the results in another
XMLList. That's pretty cool !
It also makes working with results a little easier
xml.book.title:toString() xml.book.title:toString() xml.book.author:child('lastName') xml.book.author:child('lastName')
lua-e4xis modeled after the Adobe Flex implementation.