1 unstable release
0.1.3 | Apr 4, 2024 |
---|---|
0.1.2 |
|
0.1.1 |
|
0.1.0 |
|
#93 in #xml-parser
20KB
384 lines
Note
Hello! This was a project made by Freja Roberts and want to first give credit for them. I'm still slowly updating this project because it's super intuitive but just needs updating.
Szl Simple XML
Szl Simple xml is a small crate for reading, parsing and storing xml as an extension from simple-xml. This extension adds getting mutable nodes
Usage
Example parsing:
let note =
szl_simple_xml::from_file("./examples/note.xml").expect("Failed to parse simple_xml");
let to = ¬e["to"][0];
let from = ¬e["from"][0];
let heading = ¬e.get_nodes("heading").expect("Missing heading")[0];
let body = ¬e["body"][0];
let lang = note
.get_attribute("lang")
.expect("Failed to get attribute lang");
For additional examples, please see: Docs
lib.rs
:
XML parser and writer This crate can load xml from a file or string and parse it into memory XML can also be manipulated or created and the written to file
Loading xml from a file
fn load_message() -> Result<(), simple_xml::Error> {
let root = simple_xml::from_file("examples/message.xml")?;
// Since there can multiple nodes/tags with the same name, we need to index twice
let heading = &root["heading"][0];
println!("Heading: {}", heading.content);
// Access attributes
let lang = root.get_attribute("lang").expect("Missing lang attribute");
println!("Language: {}", lang);
Ok(())
}
Creating xml structures
let name = String::from("Tim Roberts");
let health = 50;
let mut player = simple_xml::new("player", String::new());
player.add_new_node("health", health.to_string());
player.add_new_node("name", name);
// Save to file
player.save_to_file("./player.xml");
Editing xml structures
let file =
szl_simple_xml::from_file("./examples/note.xml").expect("Failed to parse simple_xml");
let mut resources =
&mut file.get_mut_nodes("resources").unwrap()[0].get_mut_nodes("resource").unwrap()[0];
let href = String::from("page1.html");
let new_file_node = szl_simple_xml::new("file", String::new());
new_file_node.add_attribute("href", &href);
resources.add_node(new_file_node);
let write_file = file.save_to_file_pretty("./test.xml")
For more example, see the tests