Sample code for 30+ languages & platforms
Zig

Find XML Element where Attribute = Value

See more XML Examples

Finds an XML element at a particular location where an attribute has a specified value.

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();

    // We have the following XML and wish to find the value of the time attribute where msg = "alert-from".

    // <cdr id="4e5d3e7f41bf6201ad81000c29703270" e164="6207">
    //     <user>
    //         <grp name="wfln" mode="active"/>
    //     </user>
    //     <event msg="setup-to" time="287069" e164="5034"/>
    //     <event msg="alert-from" time="287069" e164="5034"/>
    //     <event msg="rel-to" time="287079" e164="5034"/>
    // </cdr>

    // First, build the above XML:

    const xml = try chilkat.Xml.init();
    defer xml.deinit();
    xml.setTag("cdr");
    xml.addAttribute("id", "4e5d3e7f41bf6201ad81000c29703270") catch {};
    xml.addAttribute("e164", "6207") catch {};
    xml.updateAttrAt("user|grp", true, "name", "wfln") catch {};
    xml.updateAttrAt("user|grp", true, "mode", "active") catch {};
    xml.updateAttrAt("event", true, "msg", "setup-to") catch {};
    xml.updateAttrAt("event", true, "time", "287069") catch {};
    xml.updateAttrAt("event", true, "e164", "5034") catch {};
    xml.updateAttrAt("event[1]", true, "msg", "alert-from") catch {};
    xml.updateAttrAt("event[1]", true, "time", "287069") catch {};
    xml.updateAttrAt("event[1]", true, "e164", "5034") catch {};
    xml.updateAttrAt("event[2]", true, "msg", "rel-to") catch {};
    xml.updateAttrAt("event[2]", true, "time", "287079") catch {};
    xml.updateAttrAt("event[2]", true, "e164", "5034") catch {};

    // Show that we have the above XML
    std.debug.print("{s}\n", .{try xml.getXml(alloc)});

    // Find the element where msg = "alert-from"
    // This updates the xml object's reference to the found element (if successful).
    _ = xml.chilkatPath(alloc, "/A/event,msg,alert-from|$") catch {
        std.debug.print("Not found.\n", .{});
        return;
    };

    // Get the value of the "time" attribute.
    std.debug.print("time = {s}\n", .{try xml.getAttrValue(alloc, "time")});

    // Restore the xml object's internal reference to the root of the XML document
    xml.getRoot2();
}