Created
January 21, 2016 15:30
-
-
Save jonblack/4ebbeb7e6c8b3aea6564 to your computer and use it in GitHub Desktop.
Parse XML using xml-rs
This file contains 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
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); | |
} | |
} |
This file contains 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
<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