mod compare;
pub mod enumeration;
mod fragment;
#[cfg(test)]
mod span_tests;
pub use compare::Equality;
pub use fragment::Fragment;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;
use quick_xml::XmlVersion;
use quick_xml::events::{BytesDecl, BytesRef, BytesStart, Event};
use quick_xml::name::{QName, ResolveResult};
use quick_xml::reader::NsReader;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
pub max_depth: usize,
pub max_nodes: usize,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_depth: 256,
max_nodes: 4_000_000,
}
}
}
impl Limits {
#[must_use]
pub const fn mobile() -> Self {
Self {
max_depth: 128,
max_nodes: 500_000,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Syntax(String),
DocType,
TooDeep,
TooManyNodes,
NoRoot,
TooLarge,
NotUtf8(String),
NoSuchNode,
UndeclaredPrefix(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Syntax(message) => write!(f, "malformed XML: {message}"),
Self::DocType => f.write_str("XML with a DOCTYPE is not allowed"),
Self::TooDeep => f.write_str("XML nesting is too deep"),
Self::TooManyNodes => f.write_str("XML has too many nodes"),
Self::NoRoot => f.write_str("XML has no root element"),
Self::TooLarge => f.write_str("XML part is larger than 4 GiB"),
Self::NotUtf8(encoding) => write!(f, "XML part is in {encoding}, not in UTF-8"),
Self::NoSuchNode => f.write_str("XML document has no such node"),
Self::UndeclaredPrefix(prefix) => {
write!(
f,
"XML fragment uses the prefix {prefix} without a declaration"
)
}
}
}
}
impl std::error::Error for Error {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NamespaceId(u32);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Name {
pub prefix: Option<String>,
pub local: String,
pub namespace: Option<NamespaceId>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Attribute {
pub name: Name,
pub value: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Element {
pub name: Name,
pub attributes: Vec<Attribute>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NodeKind {
Element(Element),
Text(String),
Other(String),
}
#[derive(Clone, Debug)]
struct Node {
kind: NodeKind,
children: Vec<NodeId>,
scope: Option<ScopeId>,
span: Span,
}
#[derive(Clone, Copy, Debug, Default)]
struct Span {
start: u32,
end: u32,
}
#[derive(Clone, Copy, Debug)]
struct ScopeId(u32);
#[derive(Clone, Debug)]
struct Scope {
outer: Option<ScopeId>,
bindings: Vec<(String, NamespaceId)>,
}
const UTF8_MARK: [u8; 3] = [0xEF, 0xBB, 0xBF];
const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
#[derive(Clone, Debug)]
pub struct Document {
nodes: Vec<Node>,
top: Vec<NodeId>,
namespaces: Vec<String>,
scopes: Vec<Scope>,
undeclared_prefixes: Vec<String>,
encoding: Option<String>,
}
impl Document {
pub fn parse(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
Builder::new(*limits, &[]).run(bytes)
}
pub fn parse_with_aliases(
bytes: &[u8],
limits: &Limits,
aliases: &[(&str, &str)],
) -> Result<Self, Error> {
Builder::new(*limits, aliases).run(bytes)
}
pub fn root(&self) -> Result<NodeId, Error> {
self.top
.iter()
.copied()
.find(|id| self.element(*id).is_some())
.ok_or(Error::NoRoot)
}
#[must_use]
pub fn kind(&self, id: NodeId) -> Option<&NodeKind> {
self.node(id).map(|node| &node.kind)
}
#[must_use]
pub fn element(&self, id: NodeId) -> Option<&Element> {
match self.kind(id)? {
NodeKind::Element(element) => Some(element),
NodeKind::Text(_) | NodeKind::Other(_) => None,
}
}
#[must_use]
pub fn text(&self, id: NodeId) -> Option<&str> {
match self.kind(id)? {
NodeKind::Text(text) => Some(text),
NodeKind::Element(_) | NodeKind::Other(_) => None,
}
}
#[must_use]
pub fn children(&self, id: NodeId) -> &[NodeId] {
self.node(id).map_or(&[], |node| node.children.as_slice())
}
pub fn child_elements(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
self.children(id)
.iter()
.copied()
.filter(|child| self.element(*child).is_some())
}
pub fn set_children(&mut self, id: NodeId, children: Vec<NodeId>) {
if let Some(node) = self.nodes.get_mut(id.0 as usize) {
node.children = children;
}
}
pub fn set_attribute(&mut self, id: NodeId, namespace: Option<&str>, local: &str, value: &str) {
let namespace = namespace.map(|uri| {
let index = self.namespaces.iter().position(|known| known == uri);
NamespaceId(
u32::try_from(index.unwrap_or_else(|| {
self.namespaces.push(uri.to_owned());
self.namespaces.len() - 1
}))
.unwrap_or(u32::MAX),
)
});
let Some(Node {
kind: NodeKind::Element(element),
..
}) = self.nodes.get_mut(id.0 as usize)
else {
return;
};
if let Some(attribute) = element.attributes.iter_mut().find(|attribute| {
attribute.name.local == local && attribute.name.namespace == namespace
}) {
value.clone_into(&mut attribute.value);
} else {
element.attributes.push(Attribute {
name: Name {
prefix: None,
local: local.to_owned(),
namespace,
},
value: value.to_owned(),
});
}
}
#[must_use]
pub fn undeclared_prefixes(&self) -> &[String] {
&self.undeclared_prefixes
}
#[must_use]
pub fn prefix_namespace(&self, id: NodeId, prefix: &str) -> Option<&str> {
self.element(id)?;
if prefix == "xml" {
return Some(XML_NAMESPACE);
}
let mut scope = self.node(id)?.scope;
while let Some(ScopeId(index)) = scope {
let found = self.scopes.get(index as usize)?;
if let Some((_, namespace)) = found.bindings.iter().find(|(name, _)| name == prefix) {
let uri = self.namespace_uri(*namespace);
return (!uri.is_empty()).then_some(uri);
}
scope = found.outer;
}
None
}
pub fn span(&self, id: NodeId) -> Result<std::ops::Range<usize>, Error> {
if let Some(encoding) = &self.encoding {
return Err(Error::NotUtf8(encoding.clone()));
}
let span = self.node(id).ok_or(Error::NoSuchNode)?.span;
Ok(span.start as usize..span.end as usize)
}
#[must_use]
pub fn namespaces_in_scope(&self, id: NodeId) -> Vec<(String, String)> {
let mut found: Vec<(String, String)> = Vec::new();
if self.element(id).is_none() {
return found;
}
let mut scope = self.node(id).and_then(|node| node.scope);
while let Some(ScopeId(index)) = scope {
let Some(outer) = self.scopes.get(index as usize) else {
break;
};
for (prefix, namespace) in &outer.bindings {
if found.iter().all(|(known, _)| known != prefix) {
found.push((prefix.clone(), self.namespace_uri(*namespace).to_owned()));
}
}
scope = outer.outer;
}
found
}
#[must_use]
pub fn namespace_uri(&self, id: NamespaceId) -> &str {
self.namespaces
.get(id.0 as usize)
.map_or("", String::as_str)
}
#[must_use]
pub fn is(&self, id: NodeId, namespace: &str, local: &str) -> bool {
self.element(id)
.is_some_and(|element| self.name_is(&element.name, Some(namespace), local))
}
#[must_use]
pub fn child(&self, id: NodeId, namespace: &str, local: &str) -> Option<NodeId> {
self.child_elements(id)
.find(|child| self.is(*child, namespace, local))
}
#[must_use]
pub fn attribute(&self, id: NodeId, namespace: Option<&str>, local: &str) -> Option<&str> {
self.element(id)?
.attributes
.iter()
.find(|attribute| self.name_is(&attribute.name, namespace, local))
.map(|attribute| attribute.value.as_str())
}
#[must_use]
pub fn text_content(&self, id: NodeId) -> String {
let mut out = String::new();
self.collect_text(id, &mut out);
out
}
fn collect_text(&self, id: NodeId, out: &mut String) {
if let Some(text) = self.text(id) {
out.push_str(text);
}
for child in self.children(id) {
self.collect_text(*child, out);
}
}
fn name_is(&self, name: &Name, namespace: Option<&str>, local: &str) -> bool {
let uri = name.namespace.map(|ns| self.namespace_uri(ns));
name.local == local && uri == namespace
}
fn node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(id.0 as usize)
}
}
struct Builder {
limits: Limits,
nodes: Vec<Node>,
top: Vec<NodeId>,
stack: Vec<NodeId>,
scope_stack: Vec<Option<ScopeId>>,
scopes: Vec<Scope>,
namespaces: Vec<String>,
namespace_ids: HashMap<String, NamespaceId>,
aliases: HashMap<String, String>,
undeclared_prefixes: Vec<String>,
undeclared_seen: HashSet<String>,
offset: u64,
skipped: u64,
encoding: Option<String>,
}
impl Builder {
fn new(limits: Limits, aliases: &[(&str, &str)]) -> Self {
Self {
limits,
nodes: Vec::new(),
top: Vec::new(),
stack: Vec::new(),
scope_stack: Vec::new(),
scopes: Vec::new(),
namespaces: Vec::new(),
namespace_ids: HashMap::new(),
aliases: aliases
.iter()
.map(|(from, to)| ((*from).to_owned(), (*to).to_owned()))
.collect(),
undeclared_prefixes: Vec::new(),
undeclared_seen: HashSet::new(),
offset: 0,
skipped: 0,
encoding: None,
}
}
fn run(mut self, bytes: &[u8]) -> Result<Document, Error> {
u32::try_from(bytes.len()).map_err(|_| Error::TooLarge)?;
if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
self.encoding = Some("UTF-16".to_owned());
}
if bytes.starts_with(&UTF8_MARK) {
self.skipped = UTF8_MARK.len() as u64;
}
let mut reader = NsReader::from_reader(bytes);
reader.config_mut().check_end_names = true;
self.nodes
.reserve((bytes.len() / 64).min(self.limits.max_nodes));
let mut buf = Vec::new();
loop {
buf.clear();
let start = self.position(&reader)?;
let (resolved, event) = reader
.read_resolved_event_into(&mut buf)
.map_err(|error| Error::Syntax(error.to_string()))?;
let namespace = self.resolve(&resolved);
let span = Span {
start,
end: self.position(&reader)?,
};
match event {
Event::Eof => break,
Event::Start(tag) => {
let id = self.start_element(&reader, &tag, namespace, span)?;
self.open(id)?;
}
Event::Empty(tag) => {
self.start_element(&reader, &tag, namespace, span)?;
}
Event::End(_) => {
if let Some(node) = self
.stack
.pop()
.and_then(|id| self.nodes.get_mut(id.0 as usize))
{
node.span.end = span.end;
}
self.scope_stack.pop();
}
other => self.leaf(other, span)?,
}
}
if self.stack.is_empty() {
Ok(Document {
nodes: self.nodes,
top: self.top,
namespaces: self.namespaces,
scopes: self.scopes,
undeclared_prefixes: self.undeclared_prefixes,
encoding: self.encoding,
})
} else {
Err(Error::Syntax("unclosed element".to_owned()))
}
}
fn position(&self, reader: &NsReader<&[u8]>) -> Result<u32, Error> {
let position = (reader.buffer_position() + self.skipped).saturating_sub(self.offset);
u32::try_from(position).map_err(|_| Error::TooLarge)
}
fn leaf(&mut self, event: Event<'_>, span: Span) -> Result<(), Error> {
match event {
Event::Text(text) => self.add_text(&text.xml10_content(), span),
Event::CData(data) => self.add_text(&data.into_inner(), span),
Event::GeneralRef(reference) => self.add_text(&resolve_reference(&reference)?, span),
Event::DocType(_) => Err(Error::DocType),
Event::Comment(comment) => {
let raw = comment.into_inner();
self.add(NodeKind::Other(format!("<!--{raw}-->")), span)
.map(|_| ())
}
Event::Decl(declaration) => {
if self.encoding.is_none() {
self.encoding = declared_encoding(&declaration);
}
self.add(NodeKind::Other(String::new()), span).map(|_| ())
}
Event::PI(_) => self.add(NodeKind::Other(String::new()), span).map(|_| ()),
Event::Start(_) | Event::Empty(_) | Event::End(_) | Event::Eof => Ok(()),
}
}
fn resolve(&mut self, resolved: &ResolveResult<'_>) -> Option<NamespaceId> {
match resolved {
ResolveResult::Bound(namespace) => Some(self.intern(namespace.as_ref())),
ResolveResult::Unbound => None,
ResolveResult::Unknown(prefix) => {
if self.undeclared_seen.insert(prefix.clone()) {
self.undeclared_prefixes.push(prefix.clone());
}
None
}
}
}
fn intern(&mut self, uri: &str) -> NamespaceId {
let uri = self.aliases.get(uri).map_or(uri, String::as_str);
if let Some(id) = self.namespace_ids.get(uri) {
return *id;
}
let id = NamespaceId(u32::try_from(self.namespaces.len()).unwrap_or(u32::MAX));
let owned = uri.to_owned();
self.namespaces.push(owned.clone());
self.namespace_ids.insert(owned, id);
id
}
fn start_element(
&mut self,
reader: &NsReader<&[u8]>,
start: &BytesStart<'_>,
namespace: Option<NamespaceId>,
span: Span,
) -> Result<NodeId, Error> {
let name = split_name(start.name(), namespace);
let mut attributes = Vec::new();
for attribute in start.attributes() {
let attribute = attribute.map_err(|error| Error::Syntax(error.to_string()))?;
let (resolved, _) = reader.resolver().resolve_attribute(attribute.key);
let namespace = self.resolve(&resolved);
let value = attribute
.normalized_value(XmlVersion::Implicit1_0)
.map_err(|error| Error::Syntax(error.to_string()))?
.into_owned();
attributes.push(Attribute {
name: split_name(attribute.key, namespace),
value,
});
}
let scope = self.scope_of(&attributes)?;
let id = self.add(NodeKind::Element(Element { name, attributes }), span)?;
if let Some(node) = self.nodes.get_mut(id.0 as usize) {
node.scope = scope;
}
Ok(id)
}
fn scope_of(&mut self, attributes: &[Attribute]) -> Result<Option<ScopeId>, Error> {
let outer = self.scope_stack.last().copied().flatten();
let declared: Vec<(String, String)> = attributes
.iter()
.filter_map(|attribute| {
let name = &attribute.name;
let prefix = match name.prefix.as_deref() {
Some("xmlns") => name.local.clone(),
None if name.local == "xmlns" => String::new(),
_ => return None,
};
Some((prefix, attribute.value.clone()))
})
.collect();
if declared.is_empty() {
return Ok(outer);
}
let bindings = declared
.into_iter()
.map(|(prefix, uri)| (prefix, self.intern(&uri)))
.collect();
let id = ScopeId(u32::try_from(self.scopes.len()).map_err(|_| Error::TooManyNodes)?);
self.scopes.push(Scope { outer, bindings });
Ok(Some(id))
}
fn add_text(&mut self, text: &str, span: Span) -> Result<(), Error> {
let last = self.siblings().last().copied();
if let Some(Node {
kind: NodeKind::Text(existing),
span: joined,
..
}) = last.and_then(|id| self.nodes.get_mut(id.0 as usize))
{
existing.push_str(text);
joined.end = span.end;
return Ok(());
}
self.add(NodeKind::Text(text.to_owned()), span).map(|_| ())
}
fn siblings(&self) -> &[NodeId] {
match self.stack.last() {
Some(parent) => self
.nodes
.get(parent.0 as usize)
.map_or(&[], |node| node.children.as_slice()),
None => &self.top,
}
}
fn add(&mut self, kind: NodeKind, span: Span) -> Result<NodeId, Error> {
if self.nodes.len() >= self.limits.max_nodes {
return Err(Error::TooManyNodes);
}
let id = NodeId(u32::try_from(self.nodes.len()).map_err(|_| Error::TooManyNodes)?);
self.nodes.push(Node {
kind,
children: Vec::new(),
scope: None,
span,
});
match self.stack.last() {
Some(parent) => {
if let Some(node) = self.nodes.get_mut(parent.0 as usize) {
node.children.push(id);
}
}
None => self.top.push(id),
}
Ok(id)
}
fn open(&mut self, id: NodeId) -> Result<(), Error> {
if self.stack.len() >= self.limits.max_depth {
return Err(Error::TooDeep);
}
self.stack.push(id);
let scope = self.nodes.get(id.0 as usize).and_then(|node| node.scope);
self.scope_stack.push(scope);
Ok(())
}
}
fn split_name(name: QName<'_>, namespace: Option<NamespaceId>) -> Name {
let local = name.local_name().as_ref().to_owned();
let prefix = name.prefix().map(|prefix| prefix.as_ref().to_owned());
Name {
prefix,
local,
namespace,
}
}
fn declared_encoding(declaration: &BytesDecl<'_>) -> Option<String> {
let name = declaration.encoding()?.ok()?;
let utf8 = name.eq_ignore_ascii_case("utf-8") || name.eq_ignore_ascii_case("utf8");
(!utf8).then(|| name.into_owned())
}
fn resolve_reference(reference: &BytesRef<'_>) -> Result<Cow<'static, str>, Error> {
if let Some(ch) = reference
.resolve_char_ref()
.map_err(|error| Error::Syntax(error.to_string()))?
{
return Ok(Cow::Owned(ch.to_string()));
}
let name: &str = reference.as_ref();
let text = match name {
"lt" => "<",
"gt" => ">",
"amp" => "&",
"apos" => "'",
"quot" => "\"",
other => return Err(Error::Syntax(format!("unknown entity &{other};"))),
};
Ok(Cow::Borrowed(text))
}
#[cfg(test)]
mod tests {
use super::{Document, Error, Limits, NodeKind};
const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
fn parse(xml: &str) -> Result<Document, Error> {
Document::parse(xml.as_bytes(), &Limits::default())
}
#[test]
fn reads_elements_attributes_and_text() {
let doc = parse(&format!(
r#"<?xml version="1.0"?><w:document xmlns:w="{W}"><w:p><w:r><w:t xml:space="preserve"> a & b A</w:t></w:r><w:jc w:val="both"/></w:p></w:document>"#
))
.unwrap();
let root = doc.root().unwrap();
assert!(doc.is(root, W, "document"));
let p = doc.child(root, W, "p").unwrap();
let t = doc.child(doc.child(p, W, "r").unwrap(), W, "t").unwrap();
assert_eq!(doc.text_content(t), " a & b A");
let jc = doc.child(p, W, "jc").unwrap();
assert_eq!(doc.attribute(jc, Some(W), "val"), Some("both"));
assert_eq!(doc.attribute(jc, None, "val"), None);
let element = doc.element(jc).unwrap();
assert_eq!(element.name.prefix.as_deref(), Some("w"));
assert_eq!(doc.namespace_uri(element.name.namespace.unwrap()), W);
}
#[test]
fn sets_the_children_of_a_node() {
let mut doc = parse("<a><b>x</b><c/><d/></a>").unwrap();
let root = doc.root().unwrap();
let [b, c, d] = [0, 1, 2].map(|i| doc.children(root)[i]);
let x = doc.children(b)[0];
doc.set_children(root, vec![d, x, b]);
doc.set_children(b, Vec::new());
assert_eq!(doc.children(root), [d, x, b]);
assert_eq!(doc.text_content(root), "x");
assert_eq!(doc.children(c), []);
let mut other = parse("<a/>").unwrap();
other.set_children(d, vec![d]);
assert_eq!(other.children(d), []);
}
#[test]
fn sets_an_attribute_of_an_element() {
let mut doc = parse(&format!(r#"<w:r xmlns:w="{W}" w:rsidR="00AB">x</w:r>"#)).unwrap();
let root = doc.root().unwrap();
doc.set_attribute(root, Some("urn:note"), "change", "3");
doc.set_attribute(root, Some(W), "rsidR", "00CD");
doc.set_attribute(root, Some("urn:note"), "change", "4");
assert_eq!(doc.attribute(root, Some("urn:note"), "change"), Some("4"));
assert_eq!(doc.attribute(root, Some(W), "rsidR"), Some("00CD"));
let text = doc.children(root)[0];
doc.set_attribute(text, None, "a", "b");
assert_eq!(doc.attribute(text, None, "a"), None);
}
#[test]
fn keeps_unprefixed_attributes_and_comments() {
let doc = parse(r#"<Relationships><!-- note --><Relationship Id="rId1" Target="a.xml"/></Relationships>"#).unwrap();
let root = doc.root().unwrap();
let rel = doc.child_elements(root).next().unwrap();
assert_eq!(doc.attribute(rel, None, "Id"), Some("rId1"));
let comment = doc.children(root)[0];
assert_eq!(
doc.kind(comment),
Some(&NodeKind::Other("<!-- note -->".to_owned()))
);
assert!(doc.text(comment).is_none());
assert!(doc.element(comment).is_none());
}
#[test]
fn joins_text_around_references_and_cdata() {
let doc = parse("<a>x<y<![CDATA[<z>]]>>'"</a>").unwrap();
let root = doc.root().unwrap();
assert_eq!(doc.children(root).len(), 1);
assert_eq!(doc.text_content(root), "x<y<z>>'\"");
}
#[test]
fn refuses_doctype_and_unknown_entities() {
assert_eq!(parse("<!DOCTYPE a><a/>").unwrap_err(), Error::DocType);
assert!(matches!(parse("<a>&bogus;</a>"), Err(Error::Syntax(_))));
assert_eq!(
parse("<!-- only -->").unwrap().root().unwrap_err(),
Error::NoRoot
);
}
#[test]
fn refuses_bad_nesting() {
assert!(matches!(parse("<a><b></a>"), Err(Error::Syntax(_))));
assert!(matches!(parse("<a>"), Err(Error::Syntax(_))));
}
fn undeclared() -> Document {
parse(&format!(
r#"<w:document xmlns:w="{W}" xml:space="preserve"><p:a q:b="1" w:c="2"/><p:d></p:d><w:e p:f="3"/></w:document>"#
))
.unwrap()
}
#[test]
fn lists_each_undeclared_prefix_once_and_gives_its_elements_no_namespace() {
let doc = undeclared();
assert_eq!(doc.undeclared_prefixes(), ["p", "q"]);
let root = doc.root().unwrap();
let [a, _, e] = [0, 1, 2].map(|i| doc.children(root)[i]);
let element = doc.element(a).unwrap();
assert_eq!(element.name.prefix.as_deref(), Some("p"));
assert_eq!(element.name.namespace, None);
assert!(doc.is(e, W, "e"));
let declared = parse(&format!(r#"<w:a xmlns:w="{W}" xml:space="preserve"/>"#)).unwrap();
assert_eq!(declared.undeclared_prefixes(), [] as [&str; 0]);
}
#[test]
fn reads_an_attribute_of_an_undeclared_prefix_as_one_without_a_prefix() {
let doc = undeclared();
let root = doc.root().unwrap();
let [a, e] = [0, 2].map(|i| doc.children(root)[i]);
assert_eq!(doc.attribute(a, None, "b"), Some("1"));
assert_eq!(doc.attribute(a, Some(W), "c"), Some("2"));
assert_eq!(doc.attribute(e, None, "f"), Some("3"));
}
#[test]
fn resolves_namespace_aliases() {
let xml = r#"<s:document xmlns:s="urn:strict"><s:body s:val="1"/></s:document>"#;
let doc =
Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
.unwrap();
let root = doc.root().unwrap();
assert!(doc.is(root, W, "document"));
let body = doc.child(root, W, "body").unwrap();
assert_eq!(doc.attribute(body, Some(W), "val"), Some("1"));
let plain = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
assert!(!plain.is(plain.root().unwrap(), W, "document"));
}
#[test]
fn binds_a_prefix_by_the_nearest_declaration_in_scope() {
let doc = parse(concat!(
r#"<a xmlns:p="urn:outer" xmlns="urn:default">"#,
r#"<b xmlns:p="urn:inner" xmlns:q="urn:q"><c/></b><d/><e xmlns=""/>t</a>"#,
))
.unwrap();
let root = doc.root().unwrap();
let [b, d, e, text] = [0, 1, 2, 3].map(|i| doc.children(root)[i]);
let c = doc.children(b)[0];
let cases = [
(root, "p", Some("urn:outer")),
(c, "p", Some("urn:inner")),
(c, "q", Some("urn:q")),
(d, "p", Some("urn:outer")),
(d, "q", None),
(c, "", Some("urn:default")),
(e, "", None),
(e, "xml", Some(super::XML_NAMESPACE)),
(text, "p", None),
(text, "xml", None),
];
for (node, prefix, namespace) in cases {
assert_eq!(
doc.prefix_namespace(node, prefix),
namespace,
"{node:?} {prefix}"
);
}
}
#[test]
fn binds_a_prefix_to_its_alias() {
let xml = r#"<a xmlns:s="urn:strict"><b/></a>"#;
let doc =
Document::parse_with_aliases(xml.as_bytes(), &Limits::default(), &[("urn:strict", W)])
.unwrap();
let b = doc.children(doc.root().unwrap())[0];
assert_eq!(doc.prefix_namespace(b, "s"), Some(W));
}
#[test]
fn enforces_limits() {
let deep = Limits {
max_depth: 2,
max_nodes: 100,
};
assert_eq!(
Document::parse(b"<a><b><c/></b></a>", &deep).map(|_| ()),
Ok(())
);
assert_eq!(
Document::parse(b"<a><b><c></c></b></a>", &deep).unwrap_err(),
Error::TooDeep
);
let few = Limits {
max_depth: 10,
max_nodes: 2,
};
assert_eq!(
Document::parse(b"<a><b/><c/></a>", &few).unwrap_err(),
Error::TooManyNodes
);
}
#[test]
fn errors_display() {
for error in [
Error::Syntax("x".into()),
Error::DocType,
Error::TooDeep,
Error::TooManyNodes,
Error::NoRoot,
] {
assert_ne!(error.to_string(), "");
}
}
}