Sample code for 30+ languages & platforms
Rust

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 Rust Downloads

Rust

let xml = chilkat::Xml::new();

// The sample input XML is available at http://www.chilkatsoft.com/data/fruit.xml
if xml.load_xml_file("fruit.xml").is_err() {
    println!("{}", xml.last_error_text());
    return;
}

//  Get the number of direct children having the tag "fruit";
let num_with_tag = xml.num_children_having_tag("fruit");

if num_with_tag > 0 {

    for i in 0..num_with_tag {
        let child = xml.get_nth_child_with_tag("fruit", i).unwrap();
        println!("{}: {} : {}", i, child.tag(), child.content());

    }

    println!("-----");

    // 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.
    for i in 0..num_with_tag {
        // Navigate to the Nth child.  
        let _ = xml.get_nth_child_with_tag2("fruit", i).is_ok();
        println!("{}: {} : {}", i, xml.tag(), xml.content());
        // Navigate back up to the parent:
        let _ = xml.get_parent2().is_ok();
    }

    println!("-----");
}