Skip to main content

Document

Struct Document 

Source
pub struct Document {
    pub version: String,
    pub encoding: String,
    pub standalone: Option<bool>,
    pub html_metadata: Option<HtmlMeta>,
    /* private fields */
}
Expand description

Document owns a Bump and a pointer to the root Node inside that Bump. The struct is self-referential and the unsafety is contained — see the module-level docs for the safety argument.

Outside this type, all node references are bounded by &self so they can never escape the Document.

Fields§

§version: String

XML declaration version (e.g. "1.0"). Defaults to "1.0" when the document had no <?xml ... ?> declaration.

§encoding: String

XML declaration encoding (e.g. "UTF-8"). Defaults to "UTF-8" when the declaration omitted encoding=… or was absent entirely.

§standalone: Option<bool>

XML declaration standalone="…" value, or None when absent.

§html_metadata: Option<HtmlMeta>

HTML-specific metadata when this document was produced by an HTML parser; None for XML documents. Use Document::is_html to discriminate.

Implementations§

Source§

impl Document

Source

pub fn source(&self) -> Option<&[u8]>

The original source bytes this document was parsed from, when the parser stashed them (the borrow-from-source path). None in pure-copy mode or for programmatically built documents. Element byte offsets (Node::source_offset) index into this buffer.

Source

pub fn root<'a>(&'a self) -> &'a Node<'a>

The document root. Lifetime is bound to &self, so node references cannot outlive the Document.

Source

pub fn memory_bytes(&self) -> usize

Approximate bytes of memory the document holds. Includes every allocation made by the parser (nodes, attributes, interned-style strings, the source slice). Useful for memory diagnostics.

Source

pub fn unparsed_entity_uri(&self, name: &str) -> Option<&str>

SYSTEM identifier of the unparsed external general entity declared as <!ENTITY name SYSTEM "uri" NDATA notation> in the source document’s DTD. Returns None when no such entity is declared. Backs XSLT 1.0 §12.4’s unparsed-entity-uri() function.

Source

pub fn unparsed_entity_public_id(&self, name: &str) -> Option<&str>

PUBLIC identifier (FPI) of the unparsed external general entity named name, when it was declared with the PUBLIC form. Backs XSLT 2.0 §16.6.3’s unparsed-entity-public-id().

Source

pub fn node_string_value_by_ptr(ptr: *const Node<'static>) -> String

String-value of a node previously allocated in some document’s arena (typically this one) and reachable by raw pointer. Used by foreign-pointer code paths (XPath’s ForeignNodeSet, EXSLT str:tokenize result nodes) where the type system can’t track the lifetime back to a Document. Returns "" for null.

SAFETY-encapsulated: the unsafe deref is contained here. The caller’s contract is that ptr was minted by some live Document::new_* (or this crate’s parser) and the underlying arena has not been freed. Passing a stale or alien pointer is undefined behavior.

Source

pub fn set_node_text_content_by_ptr( &self, node_ptr: *const Node<'static>, content: &str, )

Replace the text content of the node at node_ptr with content (allocated in this document’s arena). SAFETY-encapsulated: the caller’s contract is that node_ptr was minted by this document’s new_* (so Cell<…>::set writes into our own arena’s matching lifetime). Mismatched docs are debug-asserted at the arena boundary. Silently no-ops on null.

Source

pub fn set_node_text_content<'a>(&'a self, node: &'a Node<'a>, content: &str)

Replace the text content of node with content (allocated in this document’s arena). Safe wrapper around the Cell<…>-typed content field — handles both the lean (Cell<&str>) and the c-abi (Cell<ArenaCStr>) builds. node must be a Text / CData / Comment / Pi node that lives in this document’s arena; mismatched docs will silently store a pointer that drops with the wrong arena (debug-asserted to catch misuse early).

Source

pub fn unparsed_entities(&self) -> &Arc<HashMap<String, UnparsedEntity>>

Borrow the full unparsed-entity map by reference. Cheap to clone (it’s an Arc); used by the XSLT engine to capture a snapshot for its function dispatcher.

Source

pub fn id_attributes(&self) -> &Arc<HashMap<String, Vec<String>>>

Borrow the DTD-derived ID-attribute map: element-name → list of attribute names declared with <!ATTLIST e a ID>. Empty when the document had no DTD-typed ID attributes.

Source

pub fn idref_attributes(&self) -> &Arc<HashMap<String, Vec<String>>>

Borrow the DTD-derived IDREF-attribute map: element-name → list of attribute names declared <!ATTLIST e a IDREF> / IDREFS. Empty when the document had no DTD-typed IDREF attributes.

Source

pub fn base_url(&self) -> Option<&str>

URI the document was loaded from, if known. See the base_url field: this is the document node’s base URI for fn:base-uri() / fn:document-uri(), distinct from any host stylesheet’s static base URI.

Source

pub fn first_sibling<'a>(&'a self) -> &'a Node<'a>

First sibling in the document’s top-level chain (prolog comment / PI, or root if none). Walking next_sibling from here visits every document-level node. Equivalent to libxml2’s xmlDoc.children.

Source

pub fn is_html(&self) -> bool

True when this document was produced by an HTML parser.

Source

pub unsafe fn set_root_ptr(&mut self, node: *const Node<'static>)

Re-point the document’s root. Used by mutation APIs that replace the root post-build (libxml2’s xmlDocSetRootElement).

§Safety

node must be a valid arena-resident pointer inside self.bump, OR NULL. The previous root pointer is dropped — its target remains allocated in the arena (leaked unless still reachable via the new tree).

Source

pub unsafe fn set_first_sibling_ptr(&mut self, node: *const Node<'static>)

Set the document’s first top-level node (the head of the document-level sibling chain — prolog comments/PIs precede the root element). first_sibling returns this when non-NULL, otherwise it falls back to root.

§Safety

node must be a valid arena-resident pointer, or NULL.

Source

pub fn bump(&self) -> &Bump

Direct access to the document’s bumpalo arena.

Use to allocate new nodes/attributes/strings into the same arena that owns the existing tree. The caller is responsible for tree-invariant maintenance — e.g. when linking a freshly allocated node into the tree via append_child, the new node’s parent/sibling pointers must be wired consistently.

Source

pub fn new_element<'a>(&'a self, name: &'a str) -> &'a mut Node<'a>

Allocate a fresh element node in the document’s arena. The returned node is detached — link it into the tree via append_child.

Source

pub fn new_text<'a>(&'a self, content: &'a str) -> &'a mut Node<'a>

Allocate a text node.

Source

pub fn new_cdata<'a>(&'a self, content: &'a str) -> &'a mut Node<'a>

Allocate a CDATA section.

Source

pub fn new_comment<'a>(&'a self, content: &'a str) -> &'a mut Node<'a>

Allocate a comment node.

Source

pub fn new_pi<'a>( &'a self, target: &'a str, content: Option<&'a str>, ) -> &'a mut Node<'a>

Allocate a processing-instruction node. content is None for a PI with no data section, Some (possibly "") otherwise — see DocumentBuilder::new_pi.

Source

pub fn new_dtd_decl<'a>(&'a self, content: &'a str) -> &'a mut Node<'a>

Allocate a DTD internal-subset declaration node (raw markup declarations, newline-terminated). Mirror of DocumentBuilder::new_dtd_decl for post-parse construction.

Source

pub fn new_fragment<'a>(&'a self) -> &'a mut Node<'a>

Allocate an empty document-fragment node. Mirror of DocumentBuilder::new_fragment for post-parse construction.

Source

pub fn new_entity_ref<'a>( &'a self, name: &'a str, content: &'a str, ) -> &'a mut Node<'a>

Allocate an unresolved-entity-reference node. See DocumentBuilder::new_entity_ref for semantics.

Source

pub fn adopt_subtree<'a>(&'a self, foreign: &Node<'_>) -> &'a Node<'a>

Deep-copy a subtree from another arena into this document.

Despite the name (chosen for familiarity with DOM’s adoptNode), this is a copy, not a move — the source subtree stays in its original arena. Arenas don’t release individual allocations, so a true move isn’t representable; in practice consumers either drop the source document afterward (handing ownership semantics) or keep both copies live (template-and-reuse semantics).

Walks the source subtree depth-first. Each foreign element, text, CDATA, comment, PI, entity-reference, or document-fragment node gets a fresh allocation in self’s arena. Attributes are copied alongside their owning element.

Namespaces are not yet copied — element namespace and ns_def pointers on the result are left None. Callers that need namespace-aware adoption should set them up after the fact via bump_new_namespace + attach_ns_def (c-abi build). A future revision will resolve namespaces by URI against the target document’s existing declarations.

Returns a fresh detached node — link it into the tree via append_child.

§Examples
let scratch = Document::new();
let template = scratch.new_element("metadata");
// ... build out template subtree ...

let real_doc = parse_str("<root/>", &ParseOptions::default()).unwrap();
let adopted = real_doc.adopt_subtree(template);
real_doc.append_child(real_doc.root(), adopted);
Source

pub fn new_attribute<'a>( &'a self, name: &'a str, value: &'a str, ) -> &'a mut Attribute<'a>

Allocate an attribute (detached — link via append_attribute).

Source

pub fn append_child<'a>(&'a self, parent: &'a Node<'a>, child: &'a Node<'a>)

Link child as the last child of parent. Updates parent/sibling pointers consistently.

Source

pub fn append_attribute<'a>( &'a self, element: &'a Node<'a>, attr: &'a Attribute<'a>, )

Link attr as the last attribute on element.

Trait Implementations§

Source§

impl Debug for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Drop for Document

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Send for Document

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.