lua-e4x Documentation

Get a deeper understanding of lua-e4x.

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.

XMLList

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:

XMLNode

local title_node = xml.book.title[1]  -- 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.

XMLList

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[1].author -- only searches the first `book` element for any children `author` elements.

Same API for XMLList and XMLNode

For the most part, XMLLists and 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

XMLList

xml.book[1].title:toString()
xml.book[1].title[1]:toString()

xml.book.author:child('lastName')
xml.book.author[1]:child('lastName')

References