Last active
November 23, 2018 08:28
-
-
Save ian-p-cooke/b4d74a8459814d881c6f6510bf1c6f7b to your computer and use it in GitHub Desktop.
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 sxd_document; | |
extern crate sxd_xpath; | |
use std::error::Error; | |
use sxd_document::parser; | |
use sxd_xpath::evaluate_xpath; | |
use sxd_xpath::Value; | |
use sxd_document::dom::Document; | |
pub struct XmlFixDictionary<'a> { | |
length_tags: Vec<&'a [u8]>, | |
} | |
impl <'a> XmlFixDictionary<'a> { | |
pub fn read(document: &'a Document<'a>) -> Result<XmlFixDictionary<'a>, Box<Error>> { | |
let length_tags = Self::read_length_tags(document); | |
Ok(XmlFixDictionary { length_tags }) | |
} | |
pub fn read_length_tags(document: &'a Document<'a>) -> Vec<&'a [u8]> { | |
let mut length_tags = vec![]; | |
let fields = evaluate_xpath(document, "/fix/fields/field"); | |
if let Ok(Value::Nodeset(nodes)) = fields { | |
for node in nodes { | |
let el = node.element().unwrap(); | |
let field_type = el.attribute_value("type").unwrap(); | |
if field_type.to_lowercase() == "length" { | |
let field_name = el.attribute_value("name").unwrap(); | |
let field_number = el.attribute_value("number").unwrap(); | |
println!("{} : {} = {}", field_name, field_type, field_number); | |
length_tags.push(field_number.as_bytes()); | |
} | |
} | |
} | |
length_tags | |
} | |
pub fn is_length_tag(&self, tag: &[u8]) -> bool { | |
self.length_tags.contains(&tag) | |
} | |
} | |
fn main() -> Result<(), Box<Error>> { | |
let xml = r#"<fix><fields><field name="blah" number="1" type="LENGTH"></field><field name="blahblah" number="12" type="STRING"></field></fields></fix>"#; | |
let package = parser::parse(xml)?; | |
let document = package.as_document(); | |
let fix_dict = XmlFixDictionary::read(&document)?; | |
assert!(fix_dict.is_length_tag(b"1")); | |
assert!(!fix_dict.is_length_tag(b"12")); | |
assert!(!fix_dict.is_length_tag(b"120")); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this doesn't compile