mod parse;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
pub use parse::{parse, parse_str, ParseOptions};
pub type Atom = Arc<str>;
pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
#[derive(Clone)]
pub struct QName {
pub ns: Atom,
pub local: Atom,
pub prefix: Atom,
}
impl QName {
pub fn new(ns: &str, local: &str) -> QName {
QName {
ns: ns.into(),
local: local.into(),
prefix: "".into(),
}
}
pub fn with_prefix(ns: &str, local: &str, prefix: &str) -> QName {
QName {
ns: ns.into(),
local: local.into(),
prefix: prefix.into(),
}
}
pub fn is(&self, ns: &str, local: &str) -> bool {
&*self.local == local && &*self.ns == ns
}
pub fn clark(&self) -> String {
if self.ns.is_empty() {
self.local.to_string()
} else {
format!("{{{}}}{}", self.ns, self.local)
}
}
pub fn lexical(&self) -> String {
if self.prefix.is_empty() {
self.local.to_string()
} else {
format!("{}:{}", self.prefix, self.local)
}
}
pub fn from_clark(s: &str) -> QName {
if let Some(rest) = s.strip_prefix('{') {
if let Some(i) = rest.find('}') {
return QName::new(&rest[..i], &rest[i + 1..]);
}
}
QName::new("", s)
}
}
impl PartialEq for QName {
fn eq(&self, o: &QName) -> bool {
self.local == o.local && self.ns == o.ns
}
}
impl Eq for QName {}
impl std::hash::Hash for QName {
fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
self.ns.hash(h);
self.local.hash(h);
}
}
impl PartialOrd for QName {
fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(o))
}
}
impl Ord for QName {
fn cmp(&self, o: &Self) -> std::cmp::Ordering {
(&*self.ns, &*self.local).cmp(&(&*o.ns, &*o.local))
}
}
impl fmt::Debug for QName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.prefix.is_empty() {
write!(f, "{}", self.clark())
} else {
write!(f, "{}({})", self.lexical(), self.ns)
}
}
}
impl fmt::Display for QName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.prefix.is_empty() {
write!(f, "{}", self.clark())
} else {
write!(f, "{}", self.lexical())
}
}
}
impl serde::Serialize for QName {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.clark())
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize)]
pub struct NodeId(pub u32);
const NONE: u32 = u32::MAX;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum NodeKind {
Document,
Element,
Text,
Comment,
ProcessingInstruction,
}
#[derive(Clone, Debug)]
pub(crate) struct NodeData {
pub kind: NodeKind,
pub name: Option<QName>,
pub text: Option<Atom>,
pub parent: u32,
pub first_child: u32,
pub last_child: u32,
pub next_sibling: u32,
pub prev_sibling: u32,
pub attr_start: u32,
pub attr_end: u32,
pub ns_start: u32,
pub ns_end: u32,
pub offset: u32,
pub subtree_end: u32,
}
#[derive(Clone, Debug)]
pub struct Attribute {
pub name: QName,
pub value: Atom,
pub offset: u32,
}
pub struct Document {
pub uri: Atom,
pub(crate) nodes: Vec<NodeData>,
pub(crate) attrs: Vec<Attribute>,
pub(crate) nsdecls: Vec<(Atom, Atom)>,
pub(crate) line_starts: Vec<u32>,
pub(crate) ids: HashMap<Atom, NodeId>,
pub has_doctype: bool,
pub xml_version: Atom,
pub encoding: Atom,
}
impl fmt::Debug for Document {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Document({}, {} nodes)", self.uri, self.nodes.len())
}
}
#[derive(Clone, Debug)]
pub struct XmlError {
pub message: String,
pub line: u32,
pub col: u32,
}
impl fmt::Display for XmlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
impl std::error::Error for XmlError {}
impl Document {
pub fn root(&self) -> Node<'_> {
Node {
doc: self,
id: NodeId(0),
}
}
pub fn document_element(&self) -> Option<Node<'_>> {
self.root().children().find(|n| n.is_element())
}
pub fn node(&self, id: NodeId) -> Node<'_> {
Node { doc: self, id }
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn by_id(&self, id: &str) -> Option<Node<'_>> {
self.ids.get(id).map(|&n| self.node(n))
}
pub fn line_col(&self, offset: u32) -> (u32, u32) {
let i = match self.line_starts.binary_search(&offset) {
Ok(i) => i,
Err(i) => i - 1,
};
(i as u32 + 1, offset - self.line_starts[i] + 1)
}
pub fn elements(&self) -> impl Iterator<Item = Node<'_>> + '_ {
(0..self.nodes.len() as u32)
.filter(move |&i| self.nodes[i as usize].kind == NodeKind::Element)
.map(move |i| Node {
doc: self,
id: NodeId(i),
})
}
}
#[derive(Copy, Clone)]
pub struct Node<'a> {
pub doc: &'a Document,
pub id: NodeId,
}
impl PartialEq for Node<'_> {
fn eq(&self, o: &Self) -> bool {
self.id == o.id && std::ptr::eq(self.doc, o.doc)
}
}
impl Eq for Node<'_> {}
impl fmt::Debug for Node<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind() {
NodeKind::Element => write!(f, "<{}>@{}", self.name().lexical(), self.line()),
k => write!(f, "{:?}#{}", k, self.id.0),
}
}
}
impl<'a> Node<'a> {
#[inline]
fn d(&self) -> &'a NodeData {
&self.doc.nodes[self.id.0 as usize]
}
#[inline]
fn wrap(&self, i: u32) -> Option<Node<'a>> {
if i == NONE {
None
} else {
Some(Node {
doc: self.doc,
id: NodeId(i),
})
}
}
pub fn kind(&self) -> NodeKind {
self.d().kind
}
pub fn is_element(&self) -> bool {
self.d().kind == NodeKind::Element
}
pub fn is_text(&self) -> bool {
self.d().kind == NodeKind::Text
}
pub fn name(&self) -> &'a QName {
self.d().name.as_ref().expect("node has no name")
}
pub fn try_name(&self) -> Option<&'a QName> {
self.d().name.as_ref()
}
pub fn local(&self) -> &'a str {
self.d().name.as_ref().map(|q| &*q.local).unwrap_or("")
}
pub fn ns(&self) -> &'a str {
self.d().name.as_ref().map(|q| &*q.ns).unwrap_or("")
}
pub fn is(&self, ns: &str, local: &str) -> bool {
self.d()
.name
.as_ref()
.map(|q| q.is(ns, local))
.unwrap_or(false)
&& self.is_element()
}
pub fn text(&self) -> Option<&'a str> {
self.d().text.as_deref()
}
pub fn text_atom(&self) -> Option<&'a Atom> {
self.d().text.as_ref()
}
pub fn parent(&self) -> Option<Node<'a>> {
self.wrap(self.d().parent)
}
pub fn parent_element(&self) -> Option<Node<'a>> {
self.parent().filter(|p| p.is_element())
}
pub fn first_child(&self) -> Option<Node<'a>> {
self.wrap(self.d().first_child)
}
pub fn last_child(&self) -> Option<Node<'a>> {
self.wrap(self.d().last_child)
}
pub fn next_sibling(&self) -> Option<Node<'a>> {
self.wrap(self.d().next_sibling)
}
pub fn prev_sibling(&self) -> Option<Node<'a>> {
self.wrap(self.d().prev_sibling)
}
pub fn next_sibling_element(&self) -> Option<Node<'a>> {
let mut n = self.next_sibling();
while let Some(x) = n {
if x.is_element() {
return Some(x);
}
n = x.next_sibling();
}
None
}
pub fn children(&self) -> Children<'a> {
Children {
doc: self.doc,
next: self.d().first_child,
}
}
pub fn elements(&self) -> impl Iterator<Item = Node<'a>> + 'a {
self.children().filter(|n| n.is_element())
}
pub fn elements_named(
&self,
ns: &'a str,
local: &'a str,
) -> impl Iterator<Item = Node<'a>> + 'a {
self.children().filter(move |n| n.is(ns, local))
}
pub fn first_element_named(&self, ns: &str, local: &str) -> Option<Node<'a>> {
self.children().find(|n| n.is(ns, local))
}
pub fn descendants(&self) -> impl Iterator<Item = Node<'a>> + 'a {
let doc = self.doc;
let start = self.id.0 + 1;
let end = self.d().subtree_end;
(start..=end)
.filter(move |_| end >= start)
.map(move |i| Node { doc, id: NodeId(i) })
}
pub fn descendants_or_self(&self) -> impl Iterator<Item = Node<'a>> + 'a {
let doc = self.doc;
let start = self.id.0;
let end = self.d().subtree_end;
(start..=end).map(move |i| Node { doc, id: NodeId(i) })
}
pub fn descendant_elements(&self) -> impl Iterator<Item = Node<'a>> + 'a {
self.descendants().filter(|n| n.is_element())
}
pub fn ancestors(&self) -> impl Iterator<Item = Node<'a>> + 'a {
let mut cur = self.parent();
std::iter::from_fn(move || {
let r = cur;
cur = cur.and_then(|c| c.parent());
r
})
}
pub fn is_ancestor_of(&self, other: &Node<'_>) -> bool {
std::ptr::eq(self.doc, other.doc)
&& other.id.0 > self.id.0
&& other.id.0 <= self.d().subtree_end
}
pub fn attributes(&self) -> &'a [Attribute] {
let d = self.d();
&self.doc.attrs[d.attr_start as usize..d.attr_end as usize]
}
pub fn attr(&self, ns: &str, local: &str) -> Option<&'a str> {
self.attributes()
.iter()
.find(|a| a.name.is(ns, local))
.map(|a| &*a.value)
}
pub fn att(&self, local: &str) -> Option<&'a str> {
self.attr("", local)
}
pub fn attr_atom(&self, ns: &str, local: &str) -> Option<&'a Atom> {
self.attributes()
.iter()
.find(|a| a.name.is(ns, local))
.map(|a| &a.value)
}
pub fn ns_decls(&self) -> &'a [(Atom, Atom)] {
let d = self.d();
&self.doc.nsdecls[d.ns_start as usize..d.ns_end as usize]
}
pub fn lookup_namespace(&self, prefix: &str) -> Option<&'a str> {
if prefix == "xml" {
return Some(XML_NS);
}
let mut cur = Some(*self);
while let Some(n) = cur {
if n.is_element() {
for (p, u) in n.ns_decls().iter().rev() {
if &**p == prefix {
return if u.is_empty() { None } else { Some(&**u) };
}
}
}
cur = n.parent();
}
None
}
pub fn lookup_prefix(&self, ns: &str) -> Option<&'a str> {
let mut cur = Some(*self);
while let Some(n) = cur {
if n.is_element() {
for (p, u) in n.ns_decls().iter().rev() {
if &**u == ns && self.lookup_namespace(p) == Some(ns) {
return Some(&**p);
}
}
}
cur = n.parent();
}
None
}
pub fn in_scope_namespaces(&self) -> Vec<(Atom, Atom)> {
let mut out: Vec<(Atom, Atom)> = Vec::new();
let mut cur = Some(*self);
while let Some(n) = cur {
if n.is_element() {
for (p, u) in n.ns_decls() {
if !out.iter().any(|(q, _)| q == p) {
out.push((p.clone(), u.clone()));
}
}
}
cur = n.parent();
}
out.retain(|(_, u)| !u.is_empty());
out
}
pub fn resolve_qname(&self, lexical: &str, use_default: bool) -> Option<QName> {
let lexical = lexical.trim();
if lexical.is_empty() {
return None;
}
match lexical.split_once(':') {
Some((p, l)) => {
if p.is_empty() || l.is_empty() || l.contains(':') || !is_ncname(p) || !is_ncname(l)
{
return None;
}
let ns = self.lookup_namespace(p)?;
Some(QName::with_prefix(ns, l, p))
}
None => {
if !is_ncname(lexical) {
return None;
}
let ns = if use_default {
self.lookup_namespace("").unwrap_or("")
} else {
""
};
Some(QName::new(ns, lexical))
}
}
}
pub fn string_value(&self) -> String {
match self.kind() {
NodeKind::Text | NodeKind::Comment | NodeKind::ProcessingInstruction => {
self.text().unwrap_or("").to_string()
}
_ => {
let mut s = String::new();
for n in self.descendants() {
if n.is_text() {
s.push_str(n.text().unwrap_or(""));
}
}
s
}
}
}
pub fn child_text(&self) -> String {
let mut s = String::new();
for n in self.children() {
if n.is_text() {
s.push_str(n.text().unwrap_or(""));
}
}
s
}
pub fn base_uri(&self) -> String {
let mut bases: Vec<&str> = Vec::new();
let mut cur = Some(*self);
while let Some(n) = cur {
if n.is_element() {
if let Some(b) = n.attr(XML_NS, "base") {
bases.push(b);
}
}
cur = n.parent();
}
let mut base = self.doc.uri.to_string();
for b in bases.iter().rev() {
base = resolve_uri(&base, b);
}
base
}
pub fn lang(&self) -> Option<&'a str> {
let mut cur = Some(*self);
while let Some(n) = cur {
if n.is_element() {
if let Some(l) = n.attr(XML_NS, "lang") {
return Some(l);
}
}
cur = n.parent();
}
None
}
pub fn offset(&self) -> u32 {
self.d().offset
}
pub fn line(&self) -> u32 {
self.doc.line_col(self.d().offset).0
}
pub fn line_col(&self) -> (u32, u32) {
self.doc.line_col(self.d().offset)
}
pub fn element_index(&self) -> usize {
let mut i = 1;
let mut n = self.prev_sibling();
while let Some(x) = n {
if x.is_element() {
i += 1;
}
n = x.prev_sibling();
}
i
}
pub fn to_xml(&self) -> String {
let mut s = String::new();
serialize(*self, &mut s, true);
s
}
}
fn serialize(n: Node<'_>, out: &mut String, top: bool) {
match n.kind() {
NodeKind::Document => {
for c in n.children() {
serialize(c, out, false);
}
}
NodeKind::Text => escape_text(n.text().unwrap_or(""), out),
NodeKind::Comment => {
out.push_str("<!--");
out.push_str(n.text().unwrap_or(""));
out.push_str("-->");
}
NodeKind::ProcessingInstruction => {
out.push_str("<?");
out.push_str(n.local());
if let Some(t) = n.text() {
if !t.is_empty() {
out.push(' ');
out.push_str(t);
}
}
out.push_str("?>");
}
NodeKind::Element => {
out.push('<');
let name = n.name().lexical();
out.push_str(&name);
let decls = if top {
n.in_scope_namespaces()
} else {
n.ns_decls().to_vec()
};
for (p, u) in decls {
if p.is_empty() {
out.push_str(" xmlns=\"");
} else {
out.push_str(" xmlns:");
out.push_str(&p);
out.push_str("=\"");
}
escape_attr(&u, out);
out.push('"');
}
for a in n.attributes() {
out.push(' ');
if a.name.ns.as_ref() == XML_NS {
out.push_str("xml:");
out.push_str(&a.name.local);
} else {
out.push_str(&a.name.lexical());
}
out.push_str("=\"");
escape_attr(&a.value, out);
out.push('"');
}
if n.first_child().is_none() {
out.push_str("/>");
} else {
out.push('>');
for c in n.children() {
serialize(c, out, false);
}
out.push_str("</");
out.push_str(&name);
out.push('>');
}
}
}
}
pub fn escape_text(s: &str, out: &mut String) {
for c in s.chars() {
match c {
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'&' => out.push_str("&"),
'\r' => out.push_str("
"),
_ => out.push(c),
}
}
}
pub fn escape_attr(s: &str, out: &mut String) {
for c in s.chars() {
match c {
'<' => out.push_str("<"),
'&' => out.push_str("&"),
'"' => out.push_str("""),
'\n' => out.push_str("
"),
'\r' => out.push_str("
"),
'\t' => out.push_str("	"),
_ => out.push(c),
}
}
}
pub struct Children<'a> {
doc: &'a Document,
next: u32,
}
impl<'a> Iterator for Children<'a> {
type Item = Node<'a>;
fn next(&mut self) -> Option<Node<'a>> {
if self.next == NONE {
return None;
}
let n = Node {
doc: self.doc,
id: NodeId(self.next),
};
self.next = self.doc.nodes[self.next as usize].next_sibling;
Some(n)
}
}
pub fn is_name_start(c: char) -> bool {
matches!(c, ':' | 'A'..='Z' | '_' | 'a'..='z'
| '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}'
| '\u{370}'..='\u{37D}' | '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}'
| '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
| '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
}
pub fn is_name_char(c: char) -> bool {
is_name_start(c)
|| matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
}
pub fn is_ncname(s: &str) -> bool {
let mut it = s.chars();
match it.next() {
Some(c) if c != ':' && is_name_start(c) => it.all(|c| c != ':' && is_name_char(c)),
_ => false,
}
}
pub fn is_name(s: &str) -> bool {
let mut it = s.chars();
match it.next() {
Some(c) if is_name_start(c) => it.all(is_name_char),
_ => false,
}
}
pub fn resolve_uri(base: &str, reference: &str) -> String {
let r = reference.trim();
if r.is_empty() {
return strip_fragment(base).to_string();
}
if has_scheme(r) {
return remove_dot_segments_uri(r);
}
if r.starts_with('#') {
return format!("{}{}", strip_fragment(base), r);
}
let base = strip_fragment(base);
let (prefix, path) = split_authority(base);
if r.starts_with("//") {
let scheme = base.split_once(':').map(|(s, _)| s).unwrap_or("http");
return remove_dot_segments_uri(&format!("{}:{}", scheme, r));
}
let joined = if r.starts_with('/') {
r.to_string()
} else {
let path_no_query = path.split('?').next().unwrap_or("");
match path_no_query.rfind('/') {
Some(i) => format!("{}{}", &path_no_query[..=i], r),
None => {
if prefix.is_empty() {
r.to_string()
} else {
format!("/{}", r)
}
}
}
};
format!(
"{}{}",
prefix,
remove_dots(&collapse_slashes(prefix, &joined))
)
}
fn strip_fragment(s: &str) -> &str {
s.split('#').next().unwrap_or(s)
}
pub fn has_scheme(s: &str) -> bool {
match s.find(':') {
Some(i) if i > 1 => {
let sch = &s[..i];
sch.chars()
.next()
.map(|c| c.is_ascii_alphabetic())
.unwrap_or(false)
&& sch
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}
_ => false,
}
}
fn split_authority(s: &str) -> (&str, &str) {
if let Some(i) = s.find("://") {
let after = &s[i + 3..];
match after.find('/') {
Some(j) => (&s[..i + 3 + j], &after[j..]),
None => (s, ""),
}
} else if let Some(rest) = s.strip_prefix("file:") {
let _ = rest;
("file:", &s[5..])
} else if has_scheme(s) {
let i = s.find(':').unwrap();
(&s[..=i], &s[i + 1..])
} else {
("", s)
}
}
fn remove_dot_segments_uri(s: &str) -> String {
let (prefix, path) = split_authority(s);
format!("{}{}", prefix, remove_dots(&collapse_slashes(prefix, path)))
}
fn collapse_slashes<'a>(prefix: &str, path: &'a str) -> std::borrow::Cow<'a, str> {
let end = path.find(['?', '#']).unwrap_or(path.len());
if !(prefix.starts_with("http://") || prefix.starts_with("https://"))
|| !path[..end].contains("//")
{
return std::borrow::Cow::Borrowed(path);
}
let mut out = String::with_capacity(path.len());
let mut prev_slash = false;
for c in path[..end].chars() {
if c == '/' && prev_slash {
continue;
}
prev_slash = c == '/';
out.push(c);
}
out.push_str(&path[end..]);
std::borrow::Cow::Owned(out)
}
fn remove_dots(path: &str) -> String {
let (path, query) = match path.find('?') {
Some(i) => (&path[..i], &path[i..]),
None => (path, ""),
};
if !path.contains("./")
&& !path.ends_with("/.")
&& !path.ends_with("/..")
&& path != "."
&& path != ".."
{
return format!("{}{}", path, query);
}
let abs = path.starts_with('/');
let mut out: Vec<&str> = Vec::new();
let segs: Vec<&str> = path.split('/').collect();
let n = segs.len();
for (i, seg) in segs.iter().enumerate() {
match *seg {
"." => {
if i == n - 1 {
out.push("");
}
}
".." => {
if out.len() > 1 || (out.len() == 1 && !abs && out[0] != "..") {
if out.last() == Some(&"..") {
out.push("..");
} else {
out.pop();
}
} else if !abs {
out.push("..");
}
if i == n - 1 {
out.push("");
}
}
s => out.push(s),
}
}
let mut r = out.join("/");
if abs && !r.starts_with('/') {
r.insert(0, '/');
}
format!("{}{}", r, query)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_http_path_segments_collapse() {
assert_eq!(
resolve_uri(
"file:///p/ext_def.xml",
"http://xbrl.ifrs.org/taxonomy/2021-03-24//full_ifrs/full_ifrs-cor_2021-03-24.xsd#ifrs-full_Equity"
),
"http://xbrl.ifrs.org/taxonomy/2021-03-24/full_ifrs/full_ifrs-cor_2021-03-24.xsd#ifrs-full_Equity"
);
assert_eq!(
resolve_uri("http://a/b/c/d.xsd", "x//y.xsd"),
"http://a/b/c/x/y.xsd"
);
assert_eq!(
resolve_uri("http://a/b/c/d.xsd", "y.xsd?q=a//b#p//q"),
"http://a/b/c/y.xsd?q=a//b#p//q"
);
assert_eq!(
resolve_uri("file:///a/b.xsd", "x//y.xsd"),
"file:///a/x//y.xsd"
);
}
#[test]
fn uri_resolution() {
assert_eq!(
resolve_uri("http://a/b/c/d.xsd", "e.xml"),
"http://a/b/c/e.xml"
);
assert_eq!(
resolve_uri("http://a/b/c/d.xsd", "../e.xml"),
"http://a/b/e.xml"
);
assert_eq!(
resolve_uri("http://a/b/c/d.xsd", "/e.xml"),
"http://a/e.xml"
);
assert_eq!(
resolve_uri("file:///x/y/z.xml", "q.xsd#el"),
"file:///x/y/q.xsd#el"
);
assert_eq!(resolve_uri("/x/y/z.xml", "../q.xsd"), "/x/q.xsd");
assert_eq!(resolve_uri("x/y/z.xml", "q.xsd"), "x/y/q.xsd");
assert_eq!(
resolve_uri("http://a/b/c.xsd", "http://z/y.xsd"),
"http://z/y.xsd"
);
assert_eq!(resolve_uri("http://a/b/c.xsd", "#f"), "http://a/b/c.xsd#f");
assert_eq!(
resolve_uri("http://a/b/c/d.xsd", "./././e.xml"),
"http://a/b/c/e.xml"
);
}
#[test]
fn parse_basic() {
let d = parse_str(
"file:///t.xml",
r#"<?xml version="1.0"?>
<a xmlns="urn:a" xmlns:b="urn:b" xml:lang="en"><b:c id="x" b:k="v">t&u<![CDATA[<z>]]></b:c><!--c--><d/></a>"#,
)
.unwrap();
let a = d.document_element().unwrap();
assert!(a.is("urn:a", "a"));
let c = a.elements().next().unwrap();
assert!(c.is("urn:b", "c"));
assert_eq!(c.attr("urn:b", "k"), Some("v"));
assert_eq!(c.string_value(), "t&u<z>");
assert_eq!(c.lang(), Some("en"));
assert_eq!(d.by_id("x").unwrap().id, c.id);
assert_eq!(
c.resolve_qname("b:q", true).unwrap(),
QName::new("urn:b", "q")
);
assert_eq!(
c.resolve_qname("q", true).unwrap(),
QName::new("urn:a", "q")
);
assert_eq!(a.line(), 2);
assert_eq!(a.descendant_elements().count(), 2);
}
#[test]
fn wellformedness_errors() {
assert!(parse_str("t", "<a><b></a>").is_err());
assert!(parse_str("t", "<a x='1' x='2'/>").is_err());
assert!(parse_str("t", "<p:a/>").is_err());
assert!(parse_str("t", "<a>&foo;</a>").is_err());
assert!(parse_str("t", "<a/><b/>").is_err());
assert!(parse_str("t", "<!DOCTYPE a [<!ENTITY foo 'bar'>]><a>&foo;</a>").is_ok());
let mut d = String::from("<!DOCTYPE a [<!ENTITY l0 'lollollollollollollollollollol'>");
for i in 1..10 {
let prev = format!("&l{};", i - 1);
d.push_str(&format!("<!ENTITY l{} '{}'>", i, prev.repeat(10)));
}
d.push_str("]><a>&l9;</a>");
let e = parse_str("t", &d).unwrap_err();
assert!(
e.message.contains("entity expansion limit"),
"{}",
e.message
);
}
}