use std::borrow::Cow;
use std::fs::File;
use std::io::BufReader;
use std::io::Cursor;
use xml::attribute::OwnedAttribute;
use xml::name::OwnedName;
use xml::reader::{EventReader, XmlEvent};
use super::Controlfield;
use super::Field;
use super::Record;
use super::Subfield;
pub const MARCXML_NAMESPACE: &str = "http://www.loc.gov/MARC21/slim";
pub const MARCXML_XSI_NAMESPACE: &str = "http://www.w3.org/2001/XMLSchema-instance";
pub const MARCXML_SCHEMA_LOCATION: &str =
"http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd";
const MARCXML_RECORD_TAG_NO_FORMAT: &str = r#"<record xmlns="http://www.loc.gov/MARC21/slim" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd">"#;
const ESTIMATED_SIZE_OF_XML: usize = 2000;
pub fn escape_xml(value: &str, is_attr: bool) -> Cow<'_, str> {
if !contains_escapable_chars(value) {
return Cow::Borrowed(value);
}
let mut buf = String::with_capacity(value.len());
for c in value.chars() {
if c == '&' {
buf.push_str("&");
} else if c == '\'' && is_attr {
buf.push_str("'");
} else if c == '"' && is_attr {
buf.push_str(""");
} else if c == '>' {
buf.push_str(">");
} else if c == '<' {
buf.push_str("<");
} else if c > '~' {
let ord: u32 = c.into();
buf.push_str(format!("&#x{ord:X};").as_str());
} else {
buf.push(c);
}
}
Cow::Owned(buf)
}
fn is_marc_element(name: &OwnedName) -> bool {
matches!(name.namespace.as_deref(), None | Some(MARCXML_NAMESPACE))
}
fn attribute<'a>(attributes: &'a [OwnedAttribute], name: &str) -> Option<&'a str> {
attributes
.iter()
.find(|a| a.name.namespace.is_none() && a.name.local_name == name)
.map(|a| a.value.as_str())
}
fn is_xml_whitespace(c: char) -> bool {
matches!(c, ' ' | '\t' | '\r' | '\n')
}
fn contains_escapable_chars(value: &str) -> bool {
value.contains(|c: char| ['&', '\\', '"', '>', '<'].contains(&c) || c > '~')
}
fn format(formatted: bool, value: &mut String, depth: u8) {
if formatted {
value.push('\n');
for _ in 0..depth {
value.push(' ');
}
}
}
pub struct XmlOptions {
pub formatted: bool,
pub with_xml_declaration: bool,
}
enum Capture {
Leader,
Controlfield,
Subfield,
}
struct XmlParseContext {
record: Record,
capture: Option<Capture>,
capture_depth: usize,
text: String,
field_depth: Option<usize>,
record_complete: bool,
doc_complete: bool,
}
pub enum XmlRecordIterator {
FileReader(EventReader<BufReader<File>>),
ByteReader(EventReader<Cursor<Vec<u8>>>),
}
impl Iterator for XmlRecordIterator {
type Item = Result<Record, String>;
fn next(&mut self) -> Option<Self::Item> {
let mut context = XmlParseContext {
record: Record::new(),
capture: None,
capture_depth: 0,
text: String::new(),
field_depth: None,
record_complete: false,
doc_complete: false,
};
self.read_next(&mut context).transpose()
}
}
impl XmlRecordIterator {
fn from_file(filename: &str) -> Result<Self, String> {
match File::open(filename) {
Ok(file) => Ok(XmlRecordIterator::FileReader(EventReader::new(
BufReader::new(file),
))),
Err(e) => Err(format!("Cannot read MARCXML file: {filename} {e}")),
}
}
fn from_string(xml: &str) -> Self {
XmlRecordIterator::ByteReader(EventReader::new(Cursor::new(xml.as_bytes().to_vec())))
}
fn read_next(&mut self, context: &mut XmlParseContext) -> Result<Option<Record>, String> {
loop {
let evt_res = match *self {
XmlRecordIterator::FileReader(ref mut reader) => reader.next(),
XmlRecordIterator::ByteReader(ref mut reader) => reader.next(),
};
let evt = evt_res.map_err(|e| format!("Error processing XML: {e}"))?;
if let Err(e) = self.handle_xml_event(context, evt) {
return Err(format!("Error processing XML: {e}"));
}
if context.record_complete {
return Ok(Some(std::mem::take(&mut context.record)));
} else if context.doc_complete {
context.record = Record::new();
return Ok(None);
}
}
}
fn handle_xml_event(
&mut self,
context: &mut XmlParseContext,
evt: XmlEvent,
) -> Result<(), String> {
match evt {
XmlEvent::StartElement {
name, attributes, ..
} => {
if context.capture.is_some() {
context.capture_depth += 1;
} else if let Some(depth) = context.field_depth {
if depth == 0
&& is_marc_element(&name)
&& name.local_name == "subfield"
&& let Some(code) = attribute(&attributes, "code")
{
Self::start_subfield(context, code);
} else {
context.field_depth = Some(depth + 1);
}
} else if is_marc_element(&name) {
self.handle_start_element(context, name.local_name.as_str(), &attributes)?;
}
}
XmlEvent::Characters(text) | XmlEvent::Whitespace(text) | XmlEvent::CData(text) => {
if context.capture.is_some() {
context.text.push_str(&text);
}
}
XmlEvent::EndElement { name } => {
if context.capture.is_some() {
if context.capture_depth > 0 {
context.capture_depth -= 1;
} else {
Self::end_capture(context);
}
} else if let Some(depth) = context.field_depth {
context.field_depth = depth.checked_sub(1);
} else if is_marc_element(&name) && name.local_name.as_str() == "record" {
context.record_complete = true;
}
}
XmlEvent::EndDocument => {
context.doc_complete = true;
}
_ => {}
}
Ok(())
}
fn start_subfield(context: &mut XmlParseContext, code: &str) {
if let Some(field) = context.record.fields_mut().last_mut() {
field
.subfields_mut()
.push(Subfield::new_unchecked(code, ""));
context.capture = Some(Capture::Subfield);
}
}
fn end_capture(context: &mut XmlParseContext) {
let text = std::mem::take(&mut context.text);
let record = &mut context.record;
match context.capture.take() {
Some(Capture::Leader) => {
if !text.chars().all(is_xml_whitespace) {
record.set_leader_unchecked(text);
}
}
Some(Capture::Controlfield) => {
if let Some(cf) = record.control_fields_mut().last_mut() {
cf.set_content(text);
}
}
Some(Capture::Subfield) => {
if let Some(field) = record.fields_mut().last_mut()
&& let Some(subfield) = field.subfields_mut().last_mut()
{
subfield.set_content(text);
}
}
None => {}
}
}
fn handle_start_element(
&mut self,
context: &mut XmlParseContext,
name: &str,
attributes: &[OwnedAttribute],
) -> Result<(), String> {
let record = &mut context.record;
match name {
"leader" => context.capture = Some(Capture::Leader),
"controlfield" => {
if let Some(tag) = attribute(attributes, "tag") {
record
.control_fields_mut()
.push(Controlfield::new_unchecked(tag, ""));
context.capture = Some(Capture::Controlfield);
} else {
return Err("Controlfield has no tag".to_string());
}
}
"datafield" => {
let mut field = match attribute(attributes, "tag") {
Some(tag) => Field::new_unchecked(tag),
None => {
return Err("Data field has no tag".to_string());
}
};
if let Some(ind1) = attribute(attributes, "ind1") {
field.set_ind1_unchecked(ind1);
}
if let Some(ind2) = attribute(attributes, "ind2") {
field.set_ind2_unchecked(ind2);
}
record.fields_mut().push(field);
context.field_depth = Some(0);
}
_ => {}
}
Ok(())
}
}
impl Record {
pub fn from_xml_file(filename: &str) -> Result<XmlRecordIterator, String> {
XmlRecordIterator::from_file(filename)
}
pub fn from_xml(xml: &str) -> XmlRecordIterator {
XmlRecordIterator::from_string(xml)
}
#[deprecated(note = "See to_xml_string()")]
pub fn to_xml(&self) -> String {
self.to_xml_string()
}
pub fn to_xml_string(&self) -> String {
self.to_xml_string_ops(&XmlOptions {
formatted: false,
with_xml_declaration: false,
})
}
#[deprecated(note = "See to_xml_string_formatted()")]
pub fn to_xml_formatted(&self) -> String {
self.to_xml_string_formatted()
}
pub fn to_xml_string_formatted(&self) -> String {
self.to_xml_string_ops(&XmlOptions {
formatted: true,
with_xml_declaration: false,
})
}
#[deprecated(note = "See to_xml_string_ops()")]
pub fn to_xml_ops(&self, options: &XmlOptions) -> String {
self.to_xml_string_ops(options)
}
pub fn to_xml_string_ops(&self, options: &XmlOptions) -> String {
let mut xml = match options.with_xml_declaration {
true => String::from(r#"<?xml version="1.0"?>"#),
_ => String::with_capacity(ESTIMATED_SIZE_OF_XML),
};
if options.formatted {
xml += &format!(
"\n<record\n xmlns=\"{}\"\n xmlns:xsi=\"{}\"\n xsi:schemaLocation=\"{}\">",
MARCXML_NAMESPACE, MARCXML_XSI_NAMESPACE, MARCXML_SCHEMA_LOCATION
);
} else {
xml.push_str(MARCXML_RECORD_TAG_NO_FORMAT);
}
format(options.formatted, &mut xml, 2);
xml += &format!("<leader>{}</leader>", &escape_xml(self.leader(), false));
for cfield in self.control_fields() {
format(options.formatted, &mut xml, 2);
xml += &format!(
r#"<controlfield tag="{}">{}</controlfield>"#,
escape_xml(cfield.tag(), true),
escape_xml(cfield.content(), false),
);
}
for field in self.fields() {
format(options.formatted, &mut xml, 2);
xml += &format!(
r#"<datafield tag="{}" ind1="{}" ind2="{}">"#,
escape_xml(field.tag(), true),
escape_xml(field.ind1(), true),
escape_xml(field.ind2(), true),
);
for sf in field.subfields() {
format(options.formatted, &mut xml, 4);
xml += &format!(
r#"<subfield code="{}">{}</subfield>"#,
&escape_xml(sf.code(), true),
&escape_xml(sf.content(), false)
);
}
format(options.formatted, &mut xml, 2);
xml += "</datafield>";
}
format(options.formatted, &mut xml, 0);
xml += "</record>";
xml
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_can_parse_xml_string_with_namespace() {
let iterator = Record::from_xml(
r#"<collection xmlns="http://www.loc.gov/MARC21/slim">
<record><datafield tag="245" ind1="1" ind2="0"><subfield code="a">First title</subfield></datafield></record>
<record><datafield tag="245" ind1="1" ind2="0"><subfield code="a">Second title</subfield></datafield></record>
</collection>"#,
);
let values: Vec<String> = iterator
.map(|item| item.unwrap().get_field_values("245", "a")[0].to_owned())
.collect();
assert_eq!(
values,
["First title".to_string(), "Second title".to_string()]
);
}
#[test]
fn test_can_parse_xml_string_without_namespace() {
let iterator = Record::from_xml(
r#"<collection>
<record><datafield tag="245" ind1="1" ind2="0"><subfield code="a">First title</subfield></datafield></record>
<record><datafield tag="245" ind1="1" ind2="0"><subfield code="a">Second title</subfield></datafield></record>
</collection>"#,
);
let values: Vec<String> = iterator
.map(|item| item.unwrap().get_field_values("245", "a")[0].to_owned())
.collect();
assert_eq!(
values,
["First title".to_string(), "Second title".to_string()]
);
}
#[test]
fn test_can_parse_xml_string_without_collection() {
let iterator = Record::from_xml(
r#"<record><datafield tag="245" ind1="1" ind2="0"><subfield code="a">First title</subfield></datafield></record>
<record><datafield tag="245" ind1="1" ind2="0"><subfield code="a">Second title</subfield></datafield></record>"#,
);
let values: Vec<String> = iterator
.map(|item| item.unwrap().get_field_values("245", "a")[0].to_owned())
.collect();
assert_eq!(
values,
["First title".to_string(), "Second title".to_string()]
);
}
fn only_record(xml: &str) -> Record {
let mut records = Record::from_xml(xml);
let record = records.next().expect("a record").expect("parses");
assert!(records.next().is_none(), "one record");
record
}
fn subfields(record: &Record) -> Vec<(&str, &str)> {
record.fields()[0]
.subfields()
.iter()
.map(|sf| (sf.code(), sf.content()))
.collect()
}
#[test]
fn test_keeps_all_text_within_an_element() {
let record = only_record(
r#"<record><controlfield tag="006"> </controlfield><datafield tag="092" ind1=" " ind2=" "><subfield code="a"> </subfield><subfield code="b"><![CDATA[A & B]]></subfield><subfield code="c">X<i>Y<b>Z</b></i>W</subfield><subfield code="d">P<!-- note -->Q<?pi x?>R</subfield><subfield code="e"> C & D é </subfield><subfield code="f"></subfield><subfield code="g"/></datafield></record>"#,
);
assert_eq!(record.control_fields()[0].content(), " ");
assert_eq!(
subfields(&record),
[
("a", " "),
("b", "A & B"),
("c", "XYZW"),
("d", "PQR"),
("e", " C & D \u{e9} "),
("f", ""),
("g", ""),
]
);
}
#[test]
fn test_nested_marc_elements_add_only_text() {
let record = only_record(
r#"<record><datafield tag="092" ind1=" " ind2=" "><subfield code="a">X<subfield code="b">Y</subfield>Z</subfield><subfield code="c">W</subfield></datafield></record>"#,
);
assert_eq!(subfields(&record), [("a", "XYZ"), ("c", "W")]);
}
#[test]
fn test_ignores_elements_in_other_namespaces() {
let record = only_record(
r#"<record xmlns="http://www.loc.gov/MARC21/slim" xmlns:o="urn:other"><datafield o:tag="999" tag="092" ind1="1" ind2="2" o:ind1="9"><subfield code="a">A<o:i>B</o:i></subfield><o:subfield code="b">foreign</o:subfield><subfield xmlns="" code="c">none</subfield></datafield><o:datafield tag="093"><subfield code="a">foreign field</subfield></o:datafield><o:record/></record>"#,
);
assert_eq!(record.fields().len(), 1);
let field = &record.fields()[0];
assert_eq!((field.tag(), field.ind1(), field.ind2()), ("092", "1", "2"));
assert_eq!(subfields(&record), [("a", "AB"), ("c", "none")]);
}
#[test]
fn test_subfields_are_those_directly_within_a_data_field() {
let record = only_record(
r#"<record><subfield code="x">before any field</subfield><datafield tag="245" ind1=" " ind2=" "><subfield>no code</subfield><wrap><subfield code="y">wrapped</subfield></wrap><subfield code="a">Title</subfield></datafield><subfield code="z">between fields</subfield><datafield tag="246" ind1=" " ind2=" "/><datafield tag="500" ind1=" " ind2=" "><subfield code="a">Note</subfield></datafield></record>"#,
);
let fields: Vec<(&str, Vec<(&str, &str)>)> = record
.fields()
.iter()
.map(|f| {
let sfs = f.subfields().iter().map(|sf| (sf.code(), sf.content()));
(f.tag(), sfs.collect())
})
.collect();
assert_eq!(
fields,
[
("245", vec![("a", "Title")]),
("246", vec![]),
("500", vec![("a", "Note")]),
]
);
}
#[test]
fn test_foreign_record_end_does_not_end_the_record() {
let mut records = Record::from_xml(
r#"<collection xmlns:o="urn:other"><record><o:record></o:record><datafield tag="245" ind1=" " ind2=" "><subfield code="a">One</subfield></datafield></record><record><datafield tag="245" ind1=" " ind2=" "><subfield code="a">Two</subfield></datafield></record></collection>"#,
);
for title in ["One", "Two"] {
let record = records.next().unwrap().unwrap();
assert_eq!(record.get_field_values("245", "a"), [title]);
}
assert!(records.next().is_none());
}
#[test]
fn test_keeps_values_as_found() {
let xml = r#"<record><leader>short</leader><controlfield tag="010">c</controlfield><controlfield tag="1">d</controlfield><datafield tag="24" ind1="" ind2="10"><subfield code="">empty</subfield><subfield code="Fiction.">long</subfield><subfield code="©">multibyte</subfield></datafield></record>"#;
let record = only_record(xml);
assert_eq!(record.leader(), "short");
let tags: Vec<&str> = record.control_fields().iter().map(|cf| cf.tag()).collect();
assert_eq!(tags, ["010", "1"]);
let field = &record.fields()[0];
assert_eq!((field.tag(), field.ind1(), field.ind2()), ("24", " ", "10"));
assert_eq!(
subfields(&record),
[("", "empty"), ("Fiction.", "long"), ("\u{a9}", "multibyte")]
);
let written = record.to_xml_string();
assert_eq!(only_record(&written).to_xml_string(), written);
assert!(record.to_binary().is_err());
}
#[test]
fn test_blank_leader_keeps_the_default() {
for leader in ["<leader/>", "<leader></leader>", "<leader>\n </leader>"] {
let record = only_record(&format!("<record>{leader}</record>"));
assert_eq!(record.leader(), Record::new().leader(), "{leader:?}");
}
let record = only_record("<record><leader>00000nam a2200000 a 4500</leader></record>");
assert_eq!(record.leader(), "00000nam a2200000 a 4500");
}
#[test]
fn test_can_escape_xml_entities() {
assert_eq!(escape_xml("<", true), "<");
assert_eq!(escape_xml("&", true), "&");
assert_eq!(escape_xml("\"", true), """);
assert_eq!(escape_xml("<", false), "<");
assert_eq!(escape_xml("&", false), "&");
assert_eq!(escape_xml("É", false), "É");
}
}