use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum Content {
Text(String),
Element(Element),
}
impl Content {
pub fn as_element(&self) -> Option<&Element> {
match self {
Content::Element(e) => Some(e),
Content::Text(_) => None,
}
}
pub fn as_text(&self) -> Option<&str> {
match self {
Content::Text(t) => Some(t),
Content::Element(_) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Element {
pub name: String,
pub attrs: Vec<(String, String)>,
pub content: Vec<Content>,
}
impl Element {
pub fn attr(&self, name: &str) -> Option<&str> {
self.attrs
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
pub fn elements(&self) -> impl Iterator<Item = &Element> {
self.content.iter().filter_map(Content::as_element)
}
pub fn text(&self) -> String {
self.content.iter().filter_map(Content::as_text).collect()
}
pub fn text_chunks(&self) -> impl Iterator<Item = &str> {
self.content.iter().filter_map(Content::as_text)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError(pub String);
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ParseError {}
pub fn parse(text: &str) -> Result<Element, ParseError> {
let options = roxmltree::ParsingOptions {
allow_dtd: true,
..Default::default()
};
let doc = roxmltree::Document::parse_with_options(text, options)
.map_err(|e| ParseError(e.to_string()))?;
Ok(convert(doc.root_element()))
}
fn convert(node: roxmltree::Node<'_, '_>) -> Element {
let mut element = Element {
name: node.tag_name().name().to_owned(),
attrs: node
.attributes()
.map(|a| (attr_name(&a), a.value().to_owned()))
.collect(),
content: Vec::new(),
};
for child in node.children() {
if child.is_element() {
element.content.push(Content::Element(convert(child)));
} else if child.is_text() {
push_text(&mut element.content, child.text().unwrap_or_default());
}
}
element
}
fn attr_name(a: &roxmltree::Attribute<'_, '_>) -> String {
match a.namespace() {
Some("http://www.w3.org/XML/1998/namespace") => format!("xml:{}", a.name()),
_ => a.name().to_owned(),
}
}
fn push_text(content: &mut Vec<Content>, text: &str) {
for (i, piece) in text.split('\n').enumerate() {
if i > 0 {
append_chunk(content, "\n");
}
if !piece.is_empty() {
append_chunk(content, piece);
}
}
}
fn append_chunk(content: &mut Vec<Content>, data: &str) {
if data != "\n"
&& let Some(Content::Text(last)) = content.last_mut()
&& last != "\n"
{
last.push_str(data);
return;
}
content.push(Content::Text(data.to_owned()));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn content_model() {
let root = parse("<a x=\"1\">\n <b/>\n text & more\n</a>").expect("valid xml");
assert_eq!(root.name, "a");
assert_eq!(root.attr("x"), Some("1"));
let texts: Vec<_> = root.text_chunks().collect();
assert_eq!(texts, ["\n", " ", "\n", " text & more", "\n"]);
assert_eq!(root.elements().count(), 1);
}
#[test]
fn crlf_is_normalized() {
let root = parse("<a>x\r\ny</a>").expect("valid xml");
let texts: Vec<_> = root.text_chunks().collect();
assert_eq!(texts, ["x", "\n", "y"]);
}
}