Sample code for 30+ languages & platforms
Zig

Iterate over Direct Child Nodes by Index

See more XML Examples

Demonstrates some ways to iterate over direct child nodes by index.

The input XML, available at http://www.chilkatsoft.com/data/get_child.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 Zig Downloads

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

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

    const xml = try chilkat.Xml.init();
    defer xml.deinit();

    // The sample input XML is available at http://www.chilkatsoft.com/data/get_child.xml
    xml.loadXmlFile("get_child.xml") catch {
        std.debug.print("{s}\n", .{try xml.getLastErrorText(alloc)});
        return;
    };

    // The NumChildren property contains the number of direct
    // child nodes.  Note: The child nodes under "xyz" are NOT
    // direct children of "root".  Therefore, the "root" node has
    // 7 direct children
    std.debug.print("NumChildren = {d}\n", .{xml.getNumChildren()});

    // Iterate over the direct children by index. The first child
    // is at index 0.
    var i: i32 = 0;
    i = 0;
    while (i < xml.getNumChildren()) : (i += 1) {
        //  access the tag and content directly by index:
        std.debug.print("{d}: {s} : {s}\n", .{ i, try xml.getChildTagByIndex(alloc, i), try xml.getChildContentByIndex(alloc, i) });
    }

    std.debug.print("-----\n", .{});

    // Do the same as the above loop, but get the child node
    // and access the Tag and Content properties:
    i = 0;
    while (i < xml.getNumChildren()) : (i += 1) {
        const child = try xml.getChild(i);
        defer child.deinit();
        std.debug.print("{d}: {s} : {s}\n", .{ i, try child.getTag(alloc), try child.getContent(alloc) });
    }

    std.debug.print("-----\n", .{});

    // Do the same as the above loop, but instead of creating
    // a new object instance for each child, call GetChild2 to
    // update the object's reference instead.
    i = 0;
    while (i < xml.getNumChildren()) : (i += 1) {
        // Navigate to the Nth child.
        try xml.getChild2(i);
        std.debug.print("{d}: {s} : {s}\n", .{ i, try xml.getTag(alloc), try xml.getContent(alloc) });
        // Navigate back up to the parent:
        try xml.getParent2();
    }

    std.debug.print("-----\n", .{});

    // Notice that the Content of the "xyz" node is empty.  This is correct.
    // The "xyz" node has no Content, but 2 direct children.
}