use std::fmt::Write as _;
use oxml::{EmptyElement, Indent, SerialiseOptions};
fn main() {
let source = "<?xml version=\"1.0\"?>
<catalogue>
<book lang='en'><![CDATA[Dune & Children]]></book>
<!-- prices exclude shipping -->
</catalogue>";
let doc = oxml::parse(source).expect("the document is well-formed");
let once = doc.to_xml();
println!("once:\n{once}\n");
let twice = oxml::parse(&once).expect("output parses").to_xml();
assert_eq!(once, twice, "serialisation should be a fixed point");
println!("serialising again changed nothing\n");
let mut buffer = String::new();
doc.write_xml(&mut buffer)
.expect("writing to a String cannot fail");
assert_eq!(buffer, once);
let mut report = String::new();
let _ =
writeln!(report, "{} nodes, {} bytes of XML", doc.len(), once.len());
print!("{report}");
let nested = oxml::parse("<config><servers><host/><host/></servers><motd>hi there</motd></config>")
.expect("well-formed");
let pretty = nested.to_xml_with(SerialiseOptions {
indent: Some(Indent::Spaces(2)),
..SerialiseOptions::default()
});
println!(
"pretty-printed:
{pretty}
"
);
assert!(
pretty.contains(
"
<servers>"
),
"{pretty}"
);
assert!(
pretty.contains("<motd>hi there</motd>"),
"text content untouched: {pretty}"
);
assert_eq!(
nested.to_xml_with(SerialiseOptions::default()),
nested.to_xml()
);
let mut spaced = String::new();
nested
.write_xml_with(
&mut spaced,
SerialiseOptions {
empty_elements: EmptyElement::SelfClosingSpaced,
..SerialiseOptions::default()
},
)
.expect("writing to a String cannot fail");
assert!(spaced.contains("<host />"), "{spaced}");
}