Lua
Lua
Traverse Direct Children via FirstChild / NextSibling, or LastChild / PreviousSibling
See more XML Examples
Demonstrates some ways to iterate over direct child nodes using the FirstChild / NextSibling and LastChild / PreviousSibling methods.The input XML, available at http://www.chilkatsoft.com/data/fruit.xml, is this:
<root>
<fruit color="red">apple</fruit>
<fruit color="green">pear</fruit>
<veg color="orange">carrot</veg>
<meat animal="cow">beef</meat>
<xyz>
<fruit color="blue">blueberry</fruit>
<veg color="green">broccoli</veg>
</xyz>
<fruit color="purple">grape</fruit>
<cheese color="yellow">cheddar</cheese>
</root>
Chilkat Lua Downloads
local chilkat = require("chilkat")
local xml = chilkat.Xml.new()
local nextSibling
local prevSibling
local success = xml:load_xml_file("qa_data/xml/fruit.xml")
if not success then
print(xml.last_error_text)
return
end
-- Iterate over the direct children by using FirstChild / NextSibling
local child = xml:first_child()
local bContinue = xml.last_method_success
while bContinue do
print(child.tag .. " : " .. child.content)
nextSibling = child:next_sibling()
bContinue = child.last_method_success
child = nextSibling
end
print("-----")
-- Do the same, but with FirstChild2 / NextSibling2 to avoid
-- creating so many XML object instances:
success = xml:first_child2()
while success do
print(xml.tag .. " : " .. xml.content)
success = xml:next_sibling2()
end
-- Revert back up to the parent:
success = xml:get_parent2()
print("-----")
-- Iterate in reverse order using LastChild / PreviousSibling
child = xml:last_child()
bContinue = xml.last_method_success
while bContinue do
print(child.tag .. " : " .. child.content)
prevSibling = child:previous_sibling()
bContinue = child.last_method_success
child = prevSibling
end
print("-----")
-- Do the same, but with LastChild2 / PreviousSibling2 to avoid
-- creating so many XML object instances:
success = xml:last_child2()
while success do
print(xml.tag .. " : " .. xml.content)
success = xml:previous_sibling2()
end
-- Revert back up to the parent:
success = xml:get_parent2()