Skip to content

Instantly share code, notes, and snippets.

@AaronM04
Last active October 8, 2023 07:14
Show Gist options
  • Save AaronM04/5376ec8242d7dba89157970808764b92 to your computer and use it in GitHub Desktop.
Save AaronM04/5376ec8242d7dba89157970808764b92 to your computer and use it in GitHub Desktop.
Pretty Print XML in Rust
[package]
name = "xmlformat"
version = "0.1.0"
authors = ["aaron"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
xmltree = "0.10"
clap = "2.33"
use std::fs::File;
use std::io::{Read, Write};
use xmltree::{Element, EmitterConfig};
use clap::{App, Arg};
fn main() {
let matches = App::new("XML Format")
.args(&[
Arg::with_name("input")
.required(true)
.index(1)
.help("the input file to use"),
Arg::with_name("output")
.short("o")
.required(true)
.takes_value(true)
.help("the output file to use"),
])
.get_matches();
let out_path = matches.value_of("output").unwrap(); // unwrap OK because required arg
let in_path = matches.value_of("input").unwrap(); // unwrap OK because required arg
let mut in_file = File::open(in_path).expect("openinfile");
let mut in_contents = String::new();
in_file
.read_to_string(&mut in_contents)
.expect("readinfiletostring");
drop(in_file);
let el = Element::parse(in_contents.as_bytes()).expect("parsexml");
let mut cfg = EmitterConfig::new();
cfg.perform_indent = true;
let mut out_file = File::create(out_path).expect("createoutfile");
el.write_with_config(&mut out_file, cfg).expect("writexml");
let _ = out_file.write("\n".as_bytes());
}
@AaronM04
Copy link
Author

I appreciate the suggestion, but this gist is no longer in use, at least by me. In fact, I don't even remember writing it!

@abiriadev
Copy link

I simply wanted to leave a comment, that might be useful to some other people.
(as I came across your code while googling for several hours.)

Please feel free to disregard it if you're no longer using this code :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment