Last active
October 8, 2023 07:14
-
-
Save AaronM04/5376ec8242d7dba89157970808764b92 to your computer and use it in GitHub Desktop.
Pretty Print XML in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)