XML Processing in Webscript

Since our launch last week, we've heard from a number of users who are using Webscript to process XML. To better support that scenario, we've recently added support for the LuaExpat module, which is the most popular XML parsing library for Lua.

LuaExpat parses XML into something called the LOM (Lua Object Model). This is the Lua equivalent of the DOM (Document Object Model), which is probably familiar to you. Here's a simple example of parsing XML with LuaExpat:

local lom = require 'lxp.lom'
local xml = '<greeting friendly="true">Hello.</greeting>'
local parsed = lom.parse(xml)
assert(parsed.tag == 'greeting')
assert(parsed[1] == 'Hello.')
assert(parsed.attr.friendly == 'true')

For more complex XML processing, we also added the xpath module to our GitHub repository. As mentioned in our previous post about modules, libraries in our lib repository can be imported without a full path.

The following example shows XPath in action, reporting the current weather for Bellevue, WA (where I live). This example is also available on our examples page:

local lom = require 'lxp.lom'
local xpath = require 'xpath'
local response = http.request {
        -- 12798885 is the "WOEID" for Bellevue, WA
        url = 'http://weather.yahooapis.com/forecastrss?w=12798885'
}
local condition =
        xpath.selectNodes(lom.parse(response.content), '//yweather:condition')[1]
return string.format(
        'Bellevue, WA is currently %s and %d degrees Farenheit.',
        condition.attr.text:lower(), condition.attr.temp)

We hope you find these new modules and examples helpful. Let us know what you think!