Zig
Zig
AddAttribute - Insert New Attribute in an XML Node
Demonstrates adding an name=value attribute to an XML element.
This example uses the XML sample file here: sample1.xml. The sample1.xml file contains this content:
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();
xml.loadXmlFile("qa_data/xml/sample1.xml") catch {
std.debug.print("{s}\n", .{try xml.getLastErrorText(alloc)});
return;
};
// Navigate to the "books" element:
xml.findChild2("books") catch {
std.debug.print("No books child found!\n", .{});
return;
};
const num_children = xml.getNumChildren();
var i: i32 = 0;
while (i < num_children) {
// Navigate to the Nth book
xml.getChild2(i) catch {};
// Display the book title:
std.debug.print("{s}\n", .{try xml.getAttrValue(alloc, "title")});
// Add a new integer attribute:
// Should never fail..
xml.addAttributeInt("bookId", i) catch {};
// Add a new unread="yes" attribute:
xml.addAttribute("unread", "yes") catch {};
// Navigate back up to the parent:
xml.getParent2() catch {};
i = i + 1;
}
// Navigate back to the document root:
xml.getRoot2();
// Save the updated document:
xml.saveXml("modified.xml") catch {
std.debug.print("{s}\n", .{try xml.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{try xml.getXml(alloc)});
}