roxml 0.4.2

Read-only, zero-copy, lazy XML reader for no_std environments, without allocation
Documentation
// Copyright © 2026 Stephan Kunz
//! Body text node — covers both plain character data and CDATA sections.

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

use crate::unescaped::Unescaped;

/// A text node in the body of an element.
///
/// Covers both plain character data and `<![CDATA[…]]>` sections; `text()`
/// always returns the text content without CDATA markers.
///
/// Leading and trailing whitespace is part of the text. Whitespace-only text
/// between markup, typically indentation, does not form a text node.
///
/// # Examples
/// ```
/// use roxml::prelude::*;
///
/// let reader = XmlReader::parse("<p>Hello <b>XML</b> &amp; <![CDATA[<world>]]></p>");
/// let texts: Vec<String> = reader
///     .root_element()?
///     .children()
///     .filter_map(|node| match node {
///         BodyNode::Text(t) => Some(t.unescaped().to_string()),
///         _ => None,
///     })
///     .collect();
/// assert_eq!(texts, ["Hello ", " & ", "<world>"]);
/// # Ok::<(), roxml::Error>(())
/// ```
#[derive(Clone)]
pub struct XmlText<'xml> {
	pub(crate) xml_text: &'xml str,
	/// Byte range of the raw source (including `<![CDATA[` / `]]>` if present).
	pub(crate) range: Range<usize>,
	/// Upper bound for sibling navigation (parent's close-tag start).
	pub(crate) content_end: usize,
}

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

	/// Raw text content. For CDATA sections the `<![CDATA[` / `]]>` markers are
	/// stripped; plain text is returned as written, with entity references
	/// such as `&amp;` not decoded. Use [`unescaped`](Self::unescaped) to
	/// decode them.
	#[must_use]
	pub fn text(&self) -> &'xml str {
		let s = &self.xml_text[self.range.clone()];
		s.strip_prefix("<![CDATA[")
			.and_then(|r| r.strip_suffix("]]>"))
			.unwrap_or(s)
	}

	/// Whether this node is a CDATA section.
	#[must_use]
	pub fn is_cdata(&self) -> bool {
		self.xml_text[self.range.clone()].starts_with("<![CDATA[")
	}

	/// Text content with entity references decoded, see [`Unescaped`].
	///
	/// CDATA sections are not decoded, only their line ends are normalized.
	///
	/// # Examples
	/// ```
	/// use roxml::XmlReader;
	///
	/// let reader = XmlReader::parse("<math>1 &lt; 2</math>");
	/// let text = reader.root_element()?.text_node().unwrap();
	/// assert_eq!(text.text(), "1 &lt; 2");
	/// assert_eq!(text.unescaped(), "1 < 2");
	/// # Ok::<(), roxml::Error>(())
	/// ```
	#[must_use]
	pub fn unescaped(&self) -> Unescaped<'xml> {
		if self.is_cdata() {
			Unescaped::from_cdata(self.text())
		} else {
			Unescaped::from_text(self.text())
		}
	}

	/// Byte range of this node in the source text (including CDATA markers).
	#[must_use]
	pub fn range(&self) -> Range<usize> {
		self.range.clone()
	}

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

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