Cotton code
69 lines · 2.8 KB · RustRaw
//! Text out of quick-xml events, the one way every parser here reads it.//!//! From quick-xml 0.38 a reference in text (`&amp;`, `&#233;`, `&nbsp;`)//! arrives as its own `Event::GeneralRef` between two `Event::Text`s, and the//! text events hold no references at all. A parser that only reads `Text`//! would quietly lose every `&` in a title, so each one also pushes//! [`reference_text`] for the references inside the element it is reading.use quick_xml::events::attributes::Attribute;use quick_xml::events::BytesRef;use quick_xml::XmlVersion;/// The text a reference stands for: `&amp;` is `&`, `&#233;` and `&#xE9;`/// are `é`. An entity XML does not predefine (`&nbsp;`, declared in a DTD/// we do not read) is kept as written, so nothing a person wrote is lost.pub fn reference_text(reference: &BytesRef<'_>) -> String {    if let Ok(Some(character)) = reference.resolve_char_ref() {        return character.to_string();    }    let Ok(name) = reference.decode() else { return String::new() };    match quick_xml::escape::resolve_predefined_entity(&name) {        Some(text) => text.to_string(),        None => format!("&{name};"),    }}/// An attribute's value with its references resolved, as XML 1.0 reads it;/// `None` when it holds a reference XML does not know.pub fn attribute_value(attribute: &Attribute<'_>) -> Option<String> {    attribute.normalized_value(XmlVersion::Implicit1_0).ok().map(|value| value.into_owned())}#[cfg(test)]mod tests {    use super::*;    use quick_xml::events::Event;    use quick_xml::Reader;    /// Every text and reference event of `xml`, joined, and the first start    /// tag's `a` attribute.    fn read(xml: &str) -> (String, Option<String>) {        let mut reader = Reader::from_str(xml);        let (mut text, mut value) = (String::new(), None);        loop {            match reader.read_event().expect("well-formed") {                Event::Start(start) if value.is_none() => {                    value = start.attributes().flatten().find(|a| a.key.as_ref() == b"a").and_then(|a| attribute_value(&a));                }                Event::Text(said) => text.push_str(&said.decode().expect("utf-8")),                Event::GeneralRef(reference) => text.push_str(&reference_text(&reference)),                Event::Eof => return (text, value),                _ => {}            }        }    }    #[test]    fn references_in_text_and_attributes_read_as_what_they_stand_for() {        let (text, value) = read(r#"<t a="Tom &amp; Jerry &#233;">Fish &amp; Chips &lt;3 caf&#xE9; &quot;x&quot;</t>"#);        assert_eq!(text, "Fish & Chips <3 café \"x\"");        assert_eq!(value.as_deref(), Some("Tom & Jerry é"));    }    #[test]    fn an_entity_xml_does_not_know_is_kept_as_written() {        let (text, _) = read("<t>a&nbsp;b</t>");        assert_eq!(text, "a&nbsp;b");    }}