Skip to content

Instantly share code, notes, and snippets.

@jonblack
Created January 21, 2016 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonblack/4ebbeb7e6c8b3aea6564 to your computer and use it in GitHub Desktop.
Save jonblack/4ebbeb7e6c8b3aea6564 to your computer and use it in GitHub Desktop.
Parse XML using xml-rs
extern crate xml;
use std::fs::File;
use std::io::BufReader;
use xml::reader::{EventReader, XmlEvent};
struct Book {
title: String,
author: String,
}
fn parse_books(filename: &str) -> Vec<Book> {
let file = File::open(filename).unwrap();
let file = BufReader::new(file);
let parser = EventReader::new(file);
let mut books = Vec::new();
let mut current_element = String::new();
for e in parser {
match e {
Ok(XmlEvent::StartElement { name, .. }) => {
if name.local_name == "book" {
let book = Book{
title: String::new(),
author: String::new(),
};
books.push(book);
}
current_element = name.local_name;
}
Ok(XmlEvent::Characters(s)) => {
match current_element.as_ref() {
"title" => {
let book = books.last_mut().unwrap();
book.title = s;
},
"author" => {
let book = books.last_mut().unwrap();
book.author = s;
},
_ => { println!("no match"); },
}
}
Err(e) => {
println!("Error: {}", e);
break;
}
_ => {}
}
}
books
}
fn main() {
let books = parse_books("test.xml");
for book in books {
println!("{} by {}", book.title, book.author);
}
}
<books>
<book>
<title>The Martian</title>
<author>Andy Weir</author>
</book>
<book>
<title>Ready Player One</title>
<author>Ernest Cline</author>
</book>
<book>
<title>Wool</title>
<author>Hugh Howey</author>
</book>
</books>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment