Sample code for 30+ languages & platforms
Zig

Serialize / Deserialize Hashtable to/from XML

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

Note: This example requires Chilkat v9.5.0.64 or later.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // Note: This example requires Chilkat v9.5.0.64 or later.

    // Add some entries to a hashtable.
    const hash_tab = try chilkat.Hashtable.init();
    defer hash_tab.deinit();

    hash_tab.addStr("aaa", "111") catch {};
    hash_tab.addStr("bbb", "222") catch {};
    hash_tab.addStr("ccc", "333") catch {};

    // Serialize to XML
    const sb = try chilkat.StringBuilder.init();
    defer sb.deinit();
    hash_tab.toXmlSb(sb) catch {};
    std.debug.print("{s}\n", .{try sb.getAsString(alloc)});
    std.debug.print("---\n", .{});

    // 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.
    const hash_tab2 = try chilkat.Hashtable.init();
    defer hash_tab2.deinit();
    hash_tab2.addFromXmlSb(sb) catch {};

    // 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.
    const s_table = try chilkat.StringTable.init();
    defer s_table.deinit();
    hash_tab2.getKeys(s_table) catch {};

    var i: i32 = 0;
    const num_keys = s_table.getCount();
    while (i < num_keys) {
        const key = try s_table.stringAt(alloc, i);
        std.debug.print("{s}: {s}\n", .{ key, try hash_tab2.lookupStr(alloc, key) });
        i = i + 1;
    }
}