//! Text out of quick-xml events, the one way every parser here reads it.//!//! From quick-xml 0.38 a reference in text (`&`, `é`, ` `)//! 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: `&` is `&`, `é` and `é`/// are `é`. An entity XML does not predefine (` `, declared in a DTD/// we do not read) is kept as written, so nothing a person wrote is lost.pubfn reference_text(reference: &BytesRef<'_>) -> String {ifletOk(Some(character)) = reference.resolve_char_ref() {return character.to_string(); }letOk(name) = reference.decode() else { returnString::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.pubfn attribute_value(attribute: &Attribute<'_>) -> Option<String> { attribute.normalized_value(XmlVersion::Implicit1_0).ok().map(|value| value.into_owned())}#[cfg(test)]mod tests {usesuper::*;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>) {letmut 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 & Jerry é">Fish & Chips <3 café "x"</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 b</t>"); assert_eq!(text, "a b"); }}