Zig
Zig
Iterate over Direct Children with a Specific Tag
See more XML Examples
Demonstrates how to iterate over direct children having a specific tag.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 Zig Downloads
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();
var i: i32 = 0;
// The sample input XML is available at http://www.chilkatsoft.com/data/fruit.xml
xml.loadXmlFile("fruit.xml") catch {
std.debug.print("{s}\n", .{try xml.getLastErrorText(alloc)});
return;
};
// Get the number of direct children having the tag "fruit";
const num_with_tag = xml.numChildrenHavingTag("fruit");
if (num_with_tag > 0) {
i = 0;
while (i < num_with_tag) : (i += 1) {
const child = try xml.getNthChildWithTag("fruit", 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 GetNthChildWithTag2 to
// update the object's reference instead.
i = 0;
while (i < num_with_tag) : (i += 1) {
// Navigate to the Nth child.
try xml.getNthChildWithTag2("fruit", 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", .{});
}
}