Rust
Rust
XML SearchForAttribute Method
See more XML Examples
Demonstrates the SearchForAttribute method.The input XML, available at http://www.chilkatsoft.com/data/fruitSearch.xml, is this:
<root>
<searchRoot>
<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>
</searchRoot>
<fruit color="red">strawberry</fruit>
<fruit color="orange">peach</fruit>
</root>
Chilkat Rust Downloads
let mut success = false;
let xml = chilkat::Xml::new();
success = xml.load_xml_file("qa_data/xml/fruitSearch.xml").is_ok();
if !success {
println!("{}", xml.last_error_text());
return;
}
// Search the sub-tree rooted at "searchRoot";
let mut x_search_root = xml.find_child("searchRoot").unwrap();
if !xml.last_method_success() {
println!("searchRoot not found, searching from root.");
x_search_root = xml.get_root().unwrap();
}
// Search for all "fruit" nodes having a color attribute
// where the name of the color ends in "e";
let mut x_begin_after = x_search_root.get_self().unwrap();
let mut x_found = x_search_root.search_for_attribute(Some(&x_begin_after), "fruit", "color", "*e").unwrap();
while x_search_root.last_method_success() {
println!("{}: {}", x_found.content(), x_found.get_attr_value("color").unwrap_or_default());
x_begin_after = x_found;
x_found = x_search_root.search_for_attribute(Some(&x_begin_after), "fruit", "color", "*e").unwrap();
}
// The correct output is:
// grape: purple
// blueberry: blue
println!("--------------------------");
// ---------------------------------------------------------------------------------
// Now do the same, but instead use SearchForAttribute2
// which updates the internal reference of the caller instead
// of returning the found node.
x_begin_after = x_search_root.get_self().unwrap();
let x_search = x_search_root.get_self().unwrap();
success = x_search.search_for_attribute2(Some(&x_begin_after), "fruit", "color", "*e").is_ok();
while success {
println!("{}: {}", x_search.content(), x_search.get_attr_value("color").unwrap_or_default());
// Copy the internal references so that the next search
// begins after the found node.
x_begin_after.copy_ref(&x_search);
x_search.copy_ref(&x_search_root);
success = x_search.search_for_attribute2(Some(&x_begin_after), "fruit", "color", "*e").is_ok();
}