Skip to content

Navigating & Querying

Every node in an XmlDocument has a NodeId (a u32). You start from the root and look up elements by id.

let root_id = document.get_root_id();
let root = document.get_element(root_id)?;
println!("{}", root.get_tag()); // local name, e.g. "catalog"
println!("{}", root.get_tag_ns()); // namespaced, e.g. "t:catalog"
// First child with a given local tag → Option<NodeId>
if let Some(title_id) = document.find_first_child(book_id, "title")? {
let title = document.get_element(title_id)?;
}
// All children with a given tag → Vec<NodeId>
if let Some(book_ids) = document.find_all_child(root_id, "book")? {
println!("{} books", book_ids.len());
}
// First descendant whose attribute matches → Option<NodeId>
if let Some(book_id) = document.find_first_by_attribute(root_id, "id", "bk101")? {
let book = document.get_element(book_id)?;
}
let element = document.get_element(book_id)?;
// By local name
if let Some(attr) = element.get_attribute("id") {
println!("{}", attr.get_value());
}
// By namespaced name, e.g. "t:lang"
if let Some(attr) = element.get_attribute_ns("t:lang") {
println!("{}", attr.get_value());
}

An element’s children are a list of XmlElementContentType values. Match on the variant you care about:

use draviavemal_xml_rs::XmlElementContentType;
if let Some(contents) = element.get_child_contents() {
for content in contents {
match content {
XmlElementContentType::Text(text) => println!("text: {text}"),
XmlElementContentType::Comment(c) => println!("comment: {c}"),
XmlElementContentType::Element((id, tag, _ns)) => {
println!("child <{tag}> id={id}");
}
}
}
}
// Count only child elements
let child_count = element.get_child_element_count()?;