### Rust XML DOM Complete Example - Building an XHTML Document Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Provides a complete example of building a valid XHTML 1.0 Strict document using the `xml_dom` crate. It demonstrates creating document type, document element, head, title, body, h1, and p elements with text content. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; fn main() { let implementation = get_implementation(); // Create document type let doctype = implementation .create_document_type( "html", Some("-//W3C//DTD XHTML 1.0 Strict//EN"), Some("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"), ) .unwrap(); // Create document let mut document_node = implementation .create_document( Some("http://www.w3.org/1999/xhtml"), Some("html"), Some(doctype), ) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); let root_elem = as_element_mut(&mut root).unwrap(); root_elem.set_attribute("lang", "en").unwrap(); // Create head section let mut head = document.create_element("head").unwrap(); let mut title = document.create_element("title").unwrap(); title.append_child(document.create_text_node("My Page")).unwrap(); head.append_child(title).unwrap(); root.append_child(head).unwrap(); // Create body section let mut body = document.create_element("body").unwrap(); let mut h1 = document.create_element("h1").unwrap(); h1.append_child(document.create_text_node("Welcome")).unwrap(); body.append_child(h1).unwrap(); let mut p = document.create_element("p").unwrap(); p.append_child(document.create_text_node("Hello, World!")).unwrap(); body.append_child(p).unwrap(); root.append_child(body).unwrap(); println!("{}", document_node); } ``` -------------------------------- ### Get DOM Implementation in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Retrieves a reference to a DOMImplementation instance, essential for bootstrapping DOM operations. This function is part of the level2 module and allows checking feature support for 'Core' and 'XML'. ```rust use xml_dom::level2::get_implementation; let implementation = get_implementation(); // Check feature support assert!(implementation.has_feature("Core", "2.0")); assert!(implementation.has_feature("XML", "1.0")); ``` -------------------------------- ### Manipulate XML Node Tree in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Provides examples of modifying the XML document tree structure using `Node::append_child`, `insert_before`, and `remove_child`. These methods allow for dynamic construction and modification of XML documents. The `xml_dom::level2` and `xml_dom::level2::convert` modules are required. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("list"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Append children let item1 = document.create_element("item").unwrap(); let item2 = document.create_element("item").unwrap(); let item3 = document.create_element("item").unwrap(); root.append_child(item1).unwrap(); root.append_child(item3.clone()).unwrap(); // Insert before existing child root.insert_before(item2, Some(item3.clone())).unwrap(); // Remove a child root.remove_child(item3).unwrap(); println!("{}", document_node); // Output: ``` -------------------------------- ### Parse XML from Reader using parser::read_reader Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Parses XML data from any type that implements `std::io::BufRead`, enabling streaming input from files or other sources. This is memory-efficient for large XML documents. Examples include parsing from a file or a string buffer. ```rust use xml_dom::parser::read_reader; use std::io::BufReader; use std::fs::File; // Parse from a file let file = File::open("document.xml").expect("File not found"); let reader = BufReader::new(file); let document = read_reader(reader).expect("Failed to parse XML"); // Or from a string via cursor use std::io::Cursor; let xml_data = ""; let cursor = Cursor::new(xml_data); let document = read_reader(cursor).expect("Failed to parse XML"); ``` -------------------------------- ### Create Processing Instructions in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Demonstrates creating processing instruction nodes, such as XML stylesheets, using `Document::create_processing_instruction`. These instructions provide information to applications processing the XML document. The `xml_dom::level2` and `xml_dom::level2::convert` modules are necessary. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); // Create processing instruction let pi = document .create_processing_instruction( "xml-stylesheet", Some("type=\"text/xsl\" href=\"style.xsl\" "), ) .unwrap(); document_node.append_child(pi).unwrap(); println!("{}", document_node); ``` -------------------------------- ### Create and Manipulate XML Document using xml_dom in Rust Source: https://github.com/johnstonskj/rust-xml_dom/blob/main/README.md Demonstrates creating a new HTML document, setting attributes, appending elements, and converting the DOM to an XML string using the xml_dom crate. It requires the `level2` and `level2::convert` modules. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; // Bootstrap; get an instance of `DOMImplementation`. let implementation = get_implementation(); // Create a `DocumentType` instance. let document_type = implementation .create_document_type( "html", Some("-//W3C//DTD XHTML 1.0 Transitional//EN"), Some("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"), ) .unwrap(); // Create a new `Document` using the document type defined above. let mut document_node = implementation .create_document( Some("http://www.w3.org/1999/xhtml"), Some("html"), Some(document_type)) .unwrap(); // Cast the returned document `RefNode` into a `RefDocument` trait reference let document = as_document_mut(&mut document_node).unwrap(); // Fetch the document's root element as a node, then cast to `RefElement`. let mut root_node = document.document_element().unwrap(); let root = as_element_mut(&mut root_node).unwrap(); // Create an `Attribute` instance on the root element. root.set_attribute("lang", "en"); // Create two child `Element`s of "html". let _head = root.append_child(document.create_element("head").unwrap()); let _body = root.append_child(document.create_element("body").unwrap()); // Display as XML. let xml = document_node.to_string(); println!("document 2: {}", xml); ``` -------------------------------- ### Create XML Document with Root Element in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Demonstrates creating a new XML document using the DOMImplementation. This method allows specifying a namespace URI, a qualified name for the root element, and an optional document type. ```rust use xml_dom::level2::*; let implementation = get_implementation(); // Create a simple document with root element "html" in XHTML namespace let document_node = implementation .create_document( Some("http://www.w3.org/1999/xhtml"), Some("html"), None, ) .unwrap(); println!("{}", document_node); // Output: ``` -------------------------------- ### Configure Document Behavior with ProcessingOptions Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Allows configuration of document creation behavior using the `ProcessingOptions` struct. Options like `set_assume_ids()` and `set_add_namespaces()` can be set to modify how the DOM handles attributes and namespaces during document creation. This requires using `get_implementation_ext`. ```rust use xml_dom::level2::*; use xml_dom::level2::ext::*; use xml_dom::level2::ext::dom_impl::get_implementation_ext; // Create options let mut options = ProcessingOptions::new(); options.set_assume_ids(); // Treat 'id' attributes as XML IDs options.set_add_namespaces(); // Auto-add namespace declarations // Create document with options let implementation = get_implementation_ext(); let document = implementation .create_document_with_options( Some("http://example.org/ns"), Some("root"), None, options, ) .unwrap(); ``` -------------------------------- ### Create Namespaced Elements in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Demonstrates the creation of XML elements that belong to a specific namespace. This involves providing both the namespace URI and the qualified name of the element when calling `create_element_ns`. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document( Some("http://www.w3.org/2000/svg"), Some("svg"), None, ) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Create a namespaced element let rect = document .create_element_ns("http://www.w3.org/2000/svg", "svg:rect") .unwrap(); root.append_child(rect).unwrap(); println!("{}", document_node); ``` -------------------------------- ### Create CDATA Sections in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Explains how to create CDATA sections using `Document::create_cdata_section`. This is useful for including content that should not be parsed as markup, such as script tags. The `xml_dom::level2` and `xml_dom::level2::convert` modules are required. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("script"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Create CDATA section with markup content let cdata = document .create_cdata_section("is allowed here") .unwrap(); root.append_child(cdata).unwrap(); println!("{}", document_node); // Output: ``` -------------------------------- ### Set Element Attributes in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Demonstrates how to set attribute values on an XML element by name using `Element::set_attribute`. It also shows how to check for attribute existence and retrieve attribute values. This requires the `xml_dom::level2` and `xml_dom::level2::convert` modules. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("html"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root_node = document.document_element().unwrap(); let root = as_element_mut(&mut root_node).unwrap(); // Set attributes root.set_attribute("lang", "en").unwrap(); root.set_attribute("class", "container").unwrap(); // Check attribute exists assert!(root.has_attribute("lang")); assert_eq!(root.get_attribute("lang"), Some("en".to_string())); println!("{}", document_node); // Output: ``` -------------------------------- ### Create Element Nodes in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Shows how to create new element nodes within a document. These elements can then be appended as children to other nodes in the document tree. Requires mutable access to the document and its elements. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root_node = document.document_element().unwrap(); // Create child elements let head = document.create_element("head").unwrap(); let body = document.create_element("body").unwrap(); // Append to root root_node.append_child(head).unwrap(); root_node.append_child(body).unwrap(); println!("{}", document_node); // Output: ``` -------------------------------- ### Create Comment Nodes in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Demonstrates the creation of XML comment nodes using `Document::create_comment`. The comment node is then appended to the root element of the document. This functionality relies on the `xml_dom::level2` and `xml_dom::level2::convert` modules. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Create comment node let comment = document.create_comment(" This is a comment "); root.append_child(comment).unwrap(); println!("{}", document_node); // Output: ``` -------------------------------- ### Create Text Nodes in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Shows how to create text nodes for element content using `Document::create_text_node`. The created text node is then appended as a child to a root element. This function requires the `xml_dom::level2` and `xml_dom::level2::convert` modules. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("message"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Create and append text content let text = document.create_text_node("Hello, World!"); root.append_child(text).unwrap(); println!("{}", document_node); // Output: Hello, World! ``` -------------------------------- ### Rust XML DOM Error Handling for Node Appending Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Demonstrates error handling when attempting to append a node from a different document using the `xml_dom` crate. It specifically catches `Error::WrongDocument` and `Error::HierarchyRequest` exceptions. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut doc1 = implementation .create_document(None, Some("doc1"), None) .unwrap(); let doc2 = implementation .create_document(None, Some("doc2"), None) .unwrap(); let document1 = as_document_mut(&mut doc1).unwrap(); let document2 = as_document(&doc2).unwrap(); // Try to append element from different document let foreign_element = document2.document_element().unwrap(); let mut root1 = document1.document_element().unwrap(); match root1.append_child(foreign_element) { Ok(_) => println!("Added successfully"), Err(Error::WrongDocument) => println!("Cannot add node from different document"), Err(Error::HierarchyRequest) => println!("Invalid hierarchy"), Err(e) => println!("Other error: {}", e), } ``` -------------------------------- ### Parse XML String to DOM using parser::read_xml Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Parses an XML string directly into a Document Object Model (DOM) structure. This function requires the `quick_parser` feature to be enabled. It handles various XML constructs including comments and CDATA sections. ```rust use xml_dom::parser::read_xml; let xml = r###" First Second content]]> "###; let document = read_xml(xml).expect("Failed to parse XML"); println!("{:#?}", document); println!("{}", document); ``` -------------------------------- ### Create Document Type Declaration in Rust Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Illustrates creating a DocumentType node, which is used for DTD declarations. This includes specifying the node name, public identifier, and system identifier. The created DocumentType can then be used when creating a new document. ```rust use xml_dom::level2::*; let implementation = get_implementation(); // Create an XHTML document type let document_type = implementation .create_document_type( "html", Some("-//W3C//DTD XHTML 1.0 Transitional//EN"), Some("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"), ) .unwrap(); // Use document type when creating a document let document_node = implementation .create_document( Some("http://www.w3.org/1999/xhtml"), Some("html"), Some(document_type), ) .unwrap(); println!("{}", document_node); // Output: ``` -------------------------------- ### Parse XML String to RefNode using xml_dom in Rust Source: https://github.com/johnstonskj/rust-xml_dom/blob/main/README.md Provides a function to parse an XML string into a `RefNode` representing the Document object. This functionality is part of the `quick_parser` feature, which is enabled by default. It returns a `Result` containing the `RefNode` or an error. ```rust pub fn read_xml(xml: AsRef) -> Result; ``` -------------------------------- ### Safe Node Casting with Type Conversion Functions Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Provides safe casting functions within the `convert` module for converting between different DOM node types (e.g., Document, Element). These functions include type checking (`is_document`, `is_element`) and safe casting (`as_document`, `as_element`), returning `Result` to handle potential type mismatches gracefully. Mutable casting is also supported. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); // Type checking assert!(is_document(&document_node)); assert!(!is_element(&document_node)); // Safe casting to Document let document = as_document(&document_node).unwrap(); let root_node = document.document_element().unwrap(); // Safe casting to Element (returns Result) assert!(is_element(&root_node)); let element = as_element(&root_node).unwrap(); println!("Tag name: {}", element.tag_name()); // Mutable casting let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root_node = document.document_element().unwrap(); let root = as_element_mut(&mut root_node).unwrap(); root.set_attribute("modified", "true").unwrap(); ``` -------------------------------- ### Find Elements by Tag Name using Document::get_elements_by_tag_name Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Returns a collection of all descendant elements that match a given tag name. Using '*' as the tag name will return all elements in the document. This is useful for iterating over elements of a specific type. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Build structure let mut parent = document.create_element("parent").unwrap(); let child1 = document.create_element("child").unwrap(); let child2 = document.create_element("child").unwrap(); parent.append_child(child1).unwrap(); parent.append_child(child2).unwrap(); root.append_child(parent).unwrap(); // Find all "child" elements let children = document.get_elements_by_tag_name("child"); assert_eq!(children.len(), 2); // Use "*" to match all elements let all_elements = document.get_elements_by_tag_name("*"); assert_eq!(all_elements.len(), 3); // parent + 2 children ``` -------------------------------- ### Find Element by ID using Document::get_element_by_id Source: https://context7.com/johnstonskj/rust-xml_dom/llms.txt Retrieves a single element from the DOM by its 'xml:id' attribute. This method is efficient for direct element access when IDs are unique. It requires the element to have an 'xml:id' attribute set. ```rust use xml_dom::level2::*; use xml_dom::level2::convert::*; let implementation = get_implementation(); let mut document_node = implementation .create_document(None, Some("root"), None) .unwrap(); let document = as_document_mut(&mut document_node).unwrap(); let mut root = document.document_element().unwrap(); // Create element with xml:id let mut item = document.create_element("item").unwrap(); let id_attr = document .create_attribute_ns("http://www.w3.org/XML/1998/namespace", "xml:id") .unwrap(); item.set_attribute_node(id_attr).unwrap(); as_element_mut(&mut item) .unwrap() .set_attribute_ns( "http://www.w3.org/XML/1998/namespace", "xml:id", "my-item", ) .unwrap(); root.append_child(item).unwrap(); // Find by ID let found = document.get_element_by_id("my-item"); assert!(found.is_some()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.