Node:query(path)method
Executes a path expression (XPath 1.0 and XSLT 1.0 standards) relative to this node and returns the results as a table of Node, or nil if no match is found.
Parameters
path
A string path expression to evaluate.
Return value
Returns the first matching Node, ornil if no match is found.
Example
local xml = require("xml")
local root = xml.encode([[
<library>
<book id="1"><title>WhiteSnow</title><author>Grimm brothers</author></book>
<book id="2"><title>Cinderella</title><author>Charles Perrault</author></book>
</library>
]])
local function query_and_print(xpath)
local nodes = root:query(xpath)
print('XPath query : "'..xpath..'"')
if nodes == nil then
print("\tNo node found")
else
for node in each(nodes) do
print("", node)
end
end
end
-- should print 2 nodes <book>
query_and_print("//book")
--- selects all <title> nodes inside <book>
--> should print 2 nodes (WhiteSnow and Cinderella)
query_and_print("//book/title")
--- selects all <author> nodes
--> should print 2 nodes(Grimm brothers and Charles Perrault)
query_and_print("//author")
--- selects all <book> nodes with attribute id="1"
--> should print 1 node (the first book)
query_and_print("//book[@id='1']")
--- selects <title> with the title text "Cinderella"
--> should print 1 node (the second book)
query_and_print("//book/title[text()='Cinderella']")
--- selects <book> whose author is "Grimm brothers"
--> should print 1 node (the second book)
query_and_print("//book[author='Grimm brothers']")