Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.64+

Serialize / Deserialize Hashtable to/from XML

Demonstrates how to seralize / deserialize a Hashtable to/from XML.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Add some entries to a hashtable.
local hashTab = chilkat.Hashtable.new()

hashTab:add_str("aaa", "111")
hashTab:add_str("bbb", "222")
hashTab:add_str("ccc", "333")

-- Serialize to XML
local sb = chilkat.StringBuilder.new()
hashTab:to_xml_sb(sb)
print(sb:get_as_string())
print("---")

-- The output is as follows.  Each hash table entry
-- is contained in an "e" node.  The entry's key
-- is in the "k" node, and the value in the "v" node.

-- <?xml version="1.0" encoding="utf8-8"?>
-- <hashtable>
-- <e><k>aaa</k><v>111</v></e>
-- <e><k>bbb</k><v>222</v></e>
-- <e><k>ccc</k><v>333</v></e>
-- </hashtable>
--

-- Now load (deserialize) into a new hash table.
local hashTab2 = chilkat.Hashtable.new()
hashTab2:add_from_xml_sb(sb)

-- Get the hash table keys, and lookup each (to show
-- that the hash table was correctly deserialized).
-- The GetKeys method can return the keys in any order.
local sTable = chilkat.StringTable.new()
hashTab2:get_keys(sTable)

local i = 0
local numKeys = sTable.count
while i < numKeys do
    local key = sTable:string_at(i)
    print(key .. ": " .. hashTab2:lookup_str(key))
    i = i + 1
end