roxml 0.4.2

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! Implementation of the body element type `XmlElement`.

use core::{fmt, ops::Range};

use crate::{
	body::BodyNode,
	helpers::{extract_tag_name, next_body_sibling, split_qname},
	xml_attribute::XmlAttributes,
};

/// An XML element node produced by zero-copy parsing.
///
/// Represents only actual XML elements (`<tag …>…</tag>` or `<tag/>`).
/// All string slices borrow from the original source passed to
/// [`XmlReader::parse`](crate::XmlReader::parse).
///
/// Navigation is lazy: [`children`](Self::children), [`first_child`](Self::first_child)
/// and [`next_sibling`](Self::next_sibling) scan the source each time they are
/// called. Locating the end of an element scans its content, so each
/// navigation step costs time proportional to the size of the element it
/// reaches.
#[derive(Clone)]
pub struct XmlElement<'xml> {
	pub(crate) xml_text: &'xml str,
	/// Range of the opening tag.
	pub(crate) open: Range<usize>,
	/// Range of the closing tag, or `open.end..open.end` for self-closing.
	pub(crate) close: Range<usize>,
	/// Upper bound for sibling navigation (parent's close-tag start, or the
	/// element's own end for the root element).
	pub(crate) content_end: usize,
}

impl<'xml> XmlElement<'xml> {
	pub(crate) fn new(xml_text: &'xml str, open: Range<usize>, close: Range<usize>, content_end: usize) -> Self {
		XmlElement {
			xml_text,
			open,
			close,
			content_end,
		}
	}

	/// Raw value of attribute `name`, or `None` if the attribute is absent.
	///
	/// `name` is compared with the qualified name as written in the source,
	/// including a namespace prefix. The value is returned as written, entity
	/// references are not decoded; use [`XmlAttribute::unescaped_value`](crate::XmlAttribute::unescaped_value) for
	/// that.
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse(r#"<a id="1" text="x &amp; y"/>"#);
	/// let root = reader.root_element()?;
	/// assert_eq!(root.attribute("id"), Some("1"));
	/// assert_eq!(root.attribute("text"), Some("x &amp; y"));
	/// assert_eq!(root.attribute("missing"), None);
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn attribute(&self, name: &str) -> Option<&'xml str> {
		self.attributes()
			.find(|a| a.name() == name)
			.map(|a| a.value())
	}

	/// Iterator over the element's attributes in source order.
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse(r#"<a x="1" y='2'/>"#);
	/// let root = reader.root_element()?;
	/// let pairs: Vec<_> = root.attributes().map(|a| (a.name(), a.value())).collect();
	/// assert_eq!(pairs, [("x", "1"), ("y", "2")]);
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn attributes(&self) -> XmlAttributes<'xml> {
		let name_len = extract_tag_name(self.xml_text, self.open.start + 1).len();
		let attr_start = self.open.start + 1 + name_len;
		let attr_end = self.open.end.saturating_sub(1);
		XmlAttributes {
			xml_text: self.xml_text,
			pos: attr_start,
			end: attr_end,
		}
	}

	/// Tag name of this element as written, including a namespace prefix.
	#[must_use]
	pub fn tag_name(&self) -> &'xml str {
		extract_tag_name(self.xml_text, self.open.start + 1)
	}

	/// Namespace prefix of the tag name, or `None` if there is none.
	///
	/// The prefix is not resolved to a namespace URI. To do that, look up the
	/// `xmlns:<prefix>` attribute on this element and its ancestors.
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse(r#"<svg:rect xmlns:svg="http://www.w3.org/2000/svg"/>"#);
	/// let root = reader.root_element()?;
	/// assert_eq!(root.tag_name(), "svg:rect");
	/// assert_eq!(root.prefix(), Some("svg"));
	/// assert_eq!(root.local_name(), "rect");
	/// assert_eq!(root.attribute("xmlns:svg"), Some("http://www.w3.org/2000/svg"));
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn prefix(&self) -> Option<&'xml str> {
		split_qname(self.tag_name()).0
	}

	/// Tag name without its namespace prefix.
	///
	/// See [`prefix`](Self::prefix) for an example.
	#[must_use]
	pub fn local_name(&self) -> &'xml str {
		split_qname(self.tag_name()).1
	}

	/// Raw content of the first text child node (plain text or CDATA), or
	/// `None` if the element has no text content.
	///
	/// Comments, processing instructions and child elements are passed over.
	/// The text is returned as described for [`XmlText::text`](crate::XmlText::text);
	/// use [`text_node`](Self::text_node) to decode entity references.
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse("<to><!-- recipient -->Alice</to>");
	/// assert_eq!(reader.root_element()?.text(), Some("Alice"));
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn text(&self) -> Option<&'xml str> {
		self.text_node().map(|t| t.text())
	}

	/// The first text child node (plain text or CDATA), or `None`.
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse("<expr>a &lt; b</expr>");
	/// let text = reader.root_element()?.text_node().unwrap();
	/// assert_eq!(text.text(), "a &lt; b");
	/// assert_eq!(text.unescaped(), "a < b");
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn text_node(&self) -> Option<crate::XmlText<'xml>> {
		self.children().find_map(|node| match node {
			BodyNode::Text(t) => Some(t),
			_ => None,
		})
	}

	/// First child node, or `None` for self-closing or empty elements.
	///
	/// Whitespace-only text is not a node, see [`BodyNode`].
	#[must_use]
	pub fn first_child(&self) -> Option<BodyNode<'xml>> {
		next_body_sibling(self.xml_text, self.open.end, self.close.start)
	}

	/// Next sibling node within the parent element, or `None`.
	///
	/// The root element has no siblings.
	#[must_use]
	pub fn next_sibling(&self) -> Option<BodyNode<'xml>> {
		next_body_sibling(self.xml_text, self.range().end, self.content_end)
	}

	/// Iterator over all direct child nodes (elements, text, comments and
	/// processing instructions).
	///
	/// Whitespace-only text is not a node, see [`BodyNode`].
	///
	/// # Examples
	/// ```
	/// use roxml::prelude::*;
	///
	/// let xml = "<list>
	///     <item>one</item>
	///     <item>two</item>
	/// </list>";
	/// let reader = XmlReader::parse(xml);
	/// let items: Vec<&str> = reader
	///     .root_element()?
	///     .children()
	///     .filter_map(|node| match node {
	///         BodyNode::Element(e) => e.text(),
	///         _ => None,
	///     })
	///     .collect();
	/// assert_eq!(items, ["one", "two"]);
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn children(&self) -> XmlChildren<'xml> {
		let end = if self.close.start <= self.open.end {
			self.open.end
		} else {
			self.close.start
		};
		XmlChildren {
			xml_text: self.xml_text,
			pos: self.open.end,
			end,
		}
	}

	/// Byte range of this element in the source text, from `<` of the open
	/// tag to `>` of the close tag.
	///
	/// Useful to take the raw source of an element, for example to store or
	/// forward it unchanged.
	///
	/// # Examples
	/// ```
	/// use roxml::prelude::*;
	///
	/// let xml = "<doc><part id='1'>raw <b>content</b></part></doc>";
	/// let reader = XmlReader::parse(xml);
	/// let Some(BodyNode::Element(part)) = reader.root_element()?.first_child() else {
	///     panic!("no part");
	/// };
	/// assert_eq!(&xml[part.range()], "<part id='1'>raw <b>content</b></part>");
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn range(&self) -> Range<usize> {
		let end = if self.close.is_empty() {
			self.open.end
		} else {
			self.close.end
		};
		self.open.start..end
	}
}

/// Iterator over the direct child nodes of an element.
#[derive(Clone)]
pub struct XmlChildren<'xml> {
	pub(crate) xml_text: &'xml str,
	pub(crate) pos: usize,
	pub(crate) end: usize,
}

impl<'xml> Iterator for XmlChildren<'xml> {
	type Item = BodyNode<'xml>;

	fn next(&mut self) -> Option<Self::Item> {
		let node = next_body_sibling(self.xml_text, self.pos, self.end)?;
		self.pos = node.range().end;
		Some(node)
	}
}

impl fmt::Debug for XmlElement<'_> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("XmlElement")
			.field("tag_name", &self.tag_name())
			.field("range", &self.range())
			.finish()
	}
}

impl fmt::Debug for XmlChildren<'_> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("XmlChildren")
			.field("range", &(self.pos..self.end))
			.finish()
	}
}