| 1 | |
| 2 | == xpath.lua == |
| 3 | |
| 4 | [http://www.keplerproject.org/luaexpat/ LuaExpat] is installed in the standard MIOS software. This Lua extension lets you create SAX-based XML parsers in Lua. [http://www.keplerproject.org/luaexpat/lom.html LOM] is one of these parsers is included in the !LuaExpat package. Given a XML document, LOM creates a nested table structure that replicates the XML structure. |
| 5 | |
| 6 | LuaXPath is a utility function that lets you use [http://www.w3.org/TR/xpath XPath] expressions to query a LOM object. |
| 7 | |
| 8 | {{{ |
| 9 | #!lua |
| 10 | require "xpath" |
| 11 | local lom = require "lxp.lom" |
| 12 | |
| 13 | local xmlTest = |
| 14 | [[ |
| 15 | #!xml |
| 16 | <?xml version="1.0" encoding="ISO-8859-1"?> |
| 17 | <root> |
| 18 | <element id="1" name="element1">text of the first element</element> |
| 19 | <element id="2" name="element2"> |
| 20 | <subelement>text of the second element</subelement> |
| 21 | </element> |
| 22 | </root> |
| 23 | ]] |
| 24 | |
| 25 | local lomobj = lom.parse(xmlTest) |
| 26 | |
| 27 | -- get all elements |
| 28 | xpath.selectNodes(lomobj,'//element') |
| 29 | -- get the subelement text |
| 30 | xpath.selectNodes(lomobj,'/root/element/subelement/text()') |
| 31 | -- get the first element |
| 32 | xpath.selectNodes(lomobj,'/root/element[@id="1"]') |
| 33 | }}} |
| 34 | |