Navigating & Querying
Every node in an XmlDocument has a
NodeId (a u32). You start from the root and
look up elements by id.
Start at the root
Section titled “Start at the root”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"Find children
Section titled “Find children”// 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());}Find by attribute
Section titled “Find by attribute”// 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)?;}Read attributes
Section titled “Read attributes”let element = document.get_element(book_id)?;
// By local nameif 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());}Read content (text, elements, comments)
Section titled “Read content (text, elements, comments)”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 elementslet child_count = element.get_child_element_count()?;