Debian Codegraph @

src/tree/node.rs

raw symbols SCIP
1 //! Node, and related, feature set
2 //!
3 use libc::{c_char, c_void};
4 use std::cell::RefCell;
5 use std::collections::{HashMap, HashSet};
6 use std::error::Error;
7 use std::ffi::{CStr, CString};
8 use std::hash::{Hash, Hasher};
9 use std::ptr;
10 use std::rc::Rc;
11 use std::str;
12
13 use crate::bindings::*;
14 use crate::c_helpers::*;
15 use crate::tree::namespace::Namespace;
16 use crate::tree::nodetype::NodeType;
17 use crate::tree::{Document, DocumentRef, DocumentWeak};
18 use crate::xpath::Context;
19
20 /// Deprecated, unused. Formerly the `Rc::strong_count` threshold consulted by
21 /// [`Node::node_ptr_mut`]. That heuristic was replaced by a
22 /// `RefCell::try_borrow_mut` check (a high clone count is not an aliasing
23 /// conflict), so this value is no longer read. Retained only for API
24 /// compatibility.
25 #[deprecated(note = "no longer used; node_ptr_mut now relies on RefCell::try_borrow_mut")]
26 pub static mut NODE_RC_MAX_GUARD: usize = 2;
27
28 /// Deprecated no-op. The strong-count guard it tuned was removed in favor of a
29 /// `RefCell::try_borrow_mut` check in [`Node::node_ptr_mut`]; calling this has
30 /// no effect. Retained so existing callers continue to compile.
31 #[deprecated(note = "no-op: node_ptr_mut now relies on RefCell::try_borrow_mut")]
32 pub fn set_node_rc_guard(_value: usize) {}
33
34 type NodeRef = Rc<RefCell<_Node>>;
35
36 /// Lifecycle state of a wrapped libxml2 node.
37 ///
38 /// The three variants correspond to disjoint lifetime-ownership regimes
39 /// that drive `_Node`'s `Drop` behavior:
40 ///
41 /// * `Linked` — the node is attached to its document tree. The owning
42 /// document's `xmlFreeDoc` will reclaim it; the wrapper must not free.
43 /// * `Unlinked` — `xmlUnlinkNode` has detached the node from its
44 /// parent/siblings, but `node->doc` still points at the source xmlDoc.
45 /// The source still owns the C allocation. The wrapper must not free
46 /// unless `node->doc` itself is NULL (a true C-level orphan).
47 /// * `RustOwned` — the caller has explicitly transferred ownership to
48 /// the Rust wrapper via `Node::set_rust_owned`. The C allocation will
49 /// be freed via `xmlFreeNode` when the last `Node` clone drops,
50 /// regardless of `node->doc`.
51 ///
52 /// The state-space is intentionally smaller than `(unlinked: bool,
53 /// rust_owned: bool)`: `(Linked, RustOwned)` is meaningless, so we make
54 /// it unrepresentable.
55 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
56 enum Linkage {
57 Linked,
58 Unlinked,
59 RustOwned,
60 }
61
62 #[derive(Debug)]
63 struct _Node {
64 /// libxml's xmlNodePtr
65 node_ptr: xmlNodePtr,
66 /// Reference to parent `Document`
67 document: DocumentWeak,
68 /// Lifecycle state — see `Linkage` for the semantics of each variant.
69 linkage: Linkage,
70 }
71
72 /// An xml node
73 #[derive(Clone, Debug)]
74 pub struct Node(NodeRef);
75
76 impl Hash for Node {
77 /// Generates a hash value from the `node_ptr` value.
78 fn hash<H: Hasher>(&self, state: &mut H) {
79 self.node_ptr().hash(state);
80 }
81 }
82
83 impl PartialEq for Node {
84 /// Two nodes are considered equal, if they point to the same xmlNode.
85 fn eq(&self, other: &Node) -> bool {
86 std::ptr::eq(self.node_ptr(), other.node_ptr())
87 }
88 }
89
90 impl Eq for Node {}
91
92 impl Drop for _Node {
93 /// Free the C node if and only if it has been detached from any
94 /// libxml2 document. The historical heuristic — "free if the wrapper
95 /// is `unlinked`" — conflates two distinct states:
96 /// * tree-detached (parent==NULL, but doc still points at the
97 /// source xmlDoc and that xmlDoc still owns the allocation), and
98 /// * Rust-owned (no document references the node; the wrapper
99 /// itself must call xmlFreeNode or memory leaks).
100 ///
101 /// Detaching a node from its parent (xmlUnlinkNode) does NOT clear
102 /// node->doc — the document still owns the underlying memory and its
103 /// xmlFreeDoc will reclaim it. When the wrapper drops, firing
104 /// xmlFreeNode in that situation is a use-after-free in waiting:
105 /// any other Rust wrapper or C-side reference to the same xmlNodePtr
106 /// (a sibling's prev/next, the document's idtable, an ID lookup that
107 /// hasn't run yet) sees freed memory.
108 ///
109 /// We now key the free on the C-level node->doc field: if it's NULL
110 /// the node is truly orphan and we own it; otherwise the source
111 /// document is the lifetime owner. This matches what xmlAddChild /
112 /// xmlDocSetRootElement / xmlSetTreeDoc actually do — they install a
113 /// doc pointer to claim ownership, and xmlUnlinkNode preserves that
114 /// pointer because it only severs sibling/parent links.
115 ///
116 /// Real-world driver: a host application that detaches sibling
117 /// subtrees from a still-live source document, copies them out via
118 /// xmlCopyNode, and then drops the wrapper for each detached
119 /// subtree. Under the old `unlinked`-based rule, every wrapper drop
120 /// fired xmlFreeNode against memory that the source doc still
121 /// considered live, corrupting its dictionary and causing the next
122 /// xmlCopyNode against a sibling to return NULL.
123 fn drop(&mut self) {
124 let node_ptr = self.node_ptr;
125 if node_ptr.is_null() {
126 return;
127 }
128 match self.linkage {
129 // Source document owns the allocation; `xmlFreeDoc` will reclaim
130 // it. Firing `xmlFreeNode` here would be a use-after-free in
131 // waiting (sibling/parent links, ID table, prev clones).
132 Linkage::Linked => {}
133 // Detached, but `node->doc` still points at the source. Free only
134 // if `node->doc` is NULL — a true C-level orphan no document will
135 // reach via tree walks.
136 Linkage::Unlinked => {
137 let still_doc_owned = unsafe {
138 let n: *const crate::bindings::_xmlNode = node_ptr as *const _;
139 !(*n).doc.is_null()
140 };
141 if !still_doc_owned {
142 unsafe { xmlFreeNode(node_ptr) };
143 }
144 }
145 // Caller took ownership; the wrapper is the sole lifetime owner.
146 Linkage::RustOwned => unsafe { xmlFreeNode(node_ptr) },
147 }
148 }
149 }
150
151 impl Node {
152 /// Create a new node, bound to a given document.
153 pub fn new(name: &str, ns: Option<Namespace>, doc: &Document) -> Result<Self, ()> {
154 // We will only allow to work with document-bound nodes for now, to avoid the problems of memory management.
155
156 let c_name = CString::new(name).unwrap();
157 let ns_ptr = match ns {
158 None => ptr::null_mut(),
159 Some(ns) => ns.ns_ptr(),
160 };
161 unsafe {
162 let node = xmlNewDocRawNode(
163 doc.doc_ptr(),
164 ns_ptr,
165 c_name.as_bytes().as_ptr(),
166 ptr::null(),
167 );
168 if node.is_null() {
169 Err(())
170 } else {
171 Ok(Node::wrap_new(node, &doc.0))
172 }
173 }
174 }
175
176 /// Immutably borrows the underlying libxml2 `xmlNodePtr` pointer
177 pub fn node_ptr(&self) -> xmlNodePtr {
178 self.0.borrow().node_ptr
179 }
180
181 /// Mutably borrows the underlying libxml2 `xmlNodePtr`.
182 ///
183 /// Returns `Err` only when this node's `RefCell` is *actively* borrowed — a
184 /// genuine re-entrant aliasing conflict on the same wrapped node. A high
185 /// `Rc::strong_count` is not a conflict and does not block the borrow: clones
186 /// are normal (the owning document caches one wrapper per node, and callers
187 /// hold their own), and all clones share a single `RefCell`, so
188 /// `try_borrow_mut` is the exact per-node exclusion check. This replaces the
189 /// former `Rc::strong_count <= NODE_RC_MAX_GUARD` heuristic, which rejected
190 /// benign clones and could panic (via `borrow_mut`) on the very conflict it
191 /// was meant to catch.
192 ///
193 /// The shared-`RefCell` invariant holds across clones and repeated accessor
194 /// calls for a node that is **linked** in the tree (both resolve to the cached
195 /// wrapper). It does not extend to an unlinked or imported node: `set_unlinked`
196 /// / `import_node` drop the pointer from the cache (its C node may be freed and
197 /// the address reused), so re-wrapping it afterwards yields an independent
198 /// `RefCell`.
199 ///
200 /// This guards the Rust wrapper, not the C node: mutations through the returned
201 /// raw pointer, and the C node's lifetime, remain the caller's responsibility.
202 pub fn node_ptr_mut(&mut self) -> Result<xmlNodePtr, String> {
203 match self.0.try_borrow_mut() {
204 Ok(inner) => Ok(inner.node_ptr),
205 // Do not touch `self.0` here (e.g. `get_name`): it is actively borrowed,
206 // so any further borrow would panic.
207 Err(_) => {
208 Err("Can not mutably reference a Node that is already actively borrowed".to_string())
209 }
210 }
211 }
212
213 /// Wrap a libxml node ptr with a Node
214 fn _wrap(node_ptr: xmlNodePtr, unlinked: bool, document: &DocumentRef) -> Node {
215 // If already seen, return saved Node
216 if let Some(node) = document.borrow().get_node(node_ptr) {
217 return node.clone();
218 }
219 // If newly encountered pointer, wrap
220 let node = _Node {
221 node_ptr,
222 document: Rc::downgrade(document),
223 linkage: if unlinked {
224 Linkage::Unlinked
225 } else {
226 Linkage::Linked
227 },
228 };
229 let wrapped_node = Node(Rc::new(RefCell::new(node)));
230 document
231 .borrow_mut()
232 .insert_node(node_ptr, wrapped_node.clone());
233 wrapped_node
234 }
235 /// Wrap a node already linked to a `document` tree
236 pub(crate) fn wrap(node_ptr: xmlNodePtr, document: &DocumentRef) -> Node {
237 Node::_wrap(node_ptr, false, document)
238 }
239 /// Wrap, a node owned by, but not yet linked to, a `document`
240 pub(crate) fn wrap_new(node_ptr: xmlNodePtr, document: &DocumentRef) -> Node {
241 Node::_wrap(node_ptr, true, document)
242 }
243
244 /// Create a new text node, bound to a given document
245 pub fn new_text(content: &str, doc: &Document) -> Result<Self, ()> {
246 // We will only allow to work with document-bound nodes for now, to avoid the problems of memory management.
247 let c_content = CString::new(content).unwrap();
248 unsafe {
249 let node = xmlNewDocText(doc.doc_ptr(), c_content.as_bytes().as_ptr());
250 if node.is_null() {
251 Err(())
252 } else {
253 Ok(Node::wrap_new(node, &doc.0))
254 }
255 }
256 }
257
258 /// Create a new comment node, bound to a given document. The returned
259 /// node is unlinked — attach it via `add_child`, `add_prev_sibling` or
260 /// `add_next_sibling`.
261 ///
262 /// Returns `Err(())` if the C string cannot be constructed (the comment
263 /// contains an embedded NUL), or if libxml2 returns NULL.
264 pub fn new_comment(content: &str, doc: &Document) -> Result<Self, ()> {
265 let c_content = CString::new(content).map_err(|_| ())?;
266 unsafe {
267 let node = xmlNewDocComment(doc.doc_ptr(), c_content.as_bytes().as_ptr());
268 if node.is_null() {
269 Err(())
270 } else {
271 Ok(Node::wrap_new(node, &doc.0))
272 }
273 }
274 }
275 /// Create a mock node, used for a placeholder argument
276 pub fn mock(doc: &Document) -> Self {
277 Node::new("mock", None, doc).unwrap()
278 }
279
280 /// Create a mock node, used for a placeholder argument
281 pub fn null() -> Self {
282 Node(Rc::new(RefCell::new(_Node {
283 node_ptr: ptr::null_mut(),
284 document: Rc::downgrade(&Document::null_ref()),
285 linkage: Linkage::Unlinked,
286 })))
287 }
288
289 /// `libc::c_void` isn't hashable and cannot be made hashable
290 pub fn to_hashable(&self) -> usize {
291 self.node_ptr() as usize
292 }
293
294 pub(crate) fn get_docref(&self) -> DocumentWeak {
295 self.0.borrow().document.clone()
296 }
297
298 /// Returns the next sibling if it exists
299 pub fn get_next_sibling(&self) -> Option<Node> {
300 let ptr = xmlNextSibling(self.node_ptr());
301 self.ptr_as_option(ptr)
302 }
303
304 /// Returns the previous sibling if it exists
305 pub fn get_prev_sibling(&self) -> Option<Node> {
306 let ptr = xmlPrevSibling(self.node_ptr());
307 self.ptr_as_option(ptr)
308 }
309
310 /// Returns the first child if it exists
311 pub fn get_first_child(&self) -> Option<Node> {
312 let ptr = xmlGetFirstChild(self.node_ptr());
313 self.ptr_as_option(ptr)
314 }
315 /// Returns the last child if it exists
316 pub fn get_last_child(&self) -> Option<Node> {
317 let ptr = unsafe { xmlGetLastChild(self.node_ptr()) };
318 self.ptr_as_option(ptr)
319 }
320
321 /// Returns the next element sibling if it exists
322 pub fn get_next_element_sibling(&self) -> Option<Node> {
323 match self.get_next_sibling() {
324 None => None,
325 Some(child) => {
326 let mut current_node = child;
327 while !current_node.is_element_node() {
328 match current_node.get_next_sibling() { Some(sibling) => {
329 current_node = sibling;
330 } _ => {
331 break;
332 }}
333 }
334 if current_node.is_element_node() {
335 Some(current_node)
336 } else {
337 None
338 }
339 }
340 }
341 }
342
343 /// Returns the previous element sibling if it exists
344 pub fn get_prev_element_sibling(&self) -> Option<Node> {
345 match self.get_prev_sibling() {
346 None => None,
347 Some(child) => {
348 let mut current_node = child;
349 while !current_node.is_element_node() {
350 match current_node.get_prev_sibling() { Some(sibling) => {
351 current_node = sibling;
352 } _ => {
353 break;
354 }}
355 }
356 if current_node.is_element_node() {
357 Some(current_node)
358 } else {
359 None
360 }
361 }
362 }
363 }
364
365 /// Returns the first element child if it exists
366 pub fn get_first_element_child(&self) -> Option<Node> {
367 match self.get_first_child() {
368 None => None,
369 Some(child) => {
370 let mut current_node = child;
371 while !current_node.is_element_node() {
372 match current_node.get_next_sibling() { Some(sibling) => {
373 current_node = sibling;
374 } _ => {
375 break;
376 }}
377 }
378 if current_node.is_element_node() {
379 Some(current_node)
380 } else {
381 None
382 }
383 }
384 }
385 }
386
387 /// Returns the last element child if it exists
388 pub fn get_last_element_child(&self) -> Option<Node> {
389 match self.get_last_child() {
390 None => None,
391 Some(child) => {
392 let mut current_node = child;
393 while !current_node.is_element_node() {
394 match current_node.get_prev_sibling() { Some(sibling) => {
395 current_node = sibling;
396 } _ => {
397 break;
398 }}
399 }
400 if current_node.is_element_node() {
401 Some(current_node)
402 } else {
403 None
404 }
405 }
406 }
407 }
408
409 /// Returns all child nodes of the given node as a vector
410 pub fn get_child_nodes(&self) -> Vec<Node> {
411 let mut children = Vec::new();
412 if let Some(first_child) = self.get_first_child() {
413 children.push(first_child);
414 while let Some(sibling) = children.last().unwrap().get_next_sibling() {
415 children.push(sibling)
416 }
417 }
418 children
419 }
420
421 /// Returns all child elements of the given node as a vector
422 pub fn get_child_elements(&self) -> Vec<Node> {
423 self
424 .get_child_nodes()
425 .into_iter()
426 .filter(|n| n.get_type() == Some(NodeType::ElementNode))
427 .collect::<Vec<Node>>()
428 }
429
430 /// Returns the parent if it exists
431 pub fn get_parent(&self) -> Option<Node> {
432 let ptr = xmlGetParent(self.node_ptr());
433 self.ptr_as_option(ptr)
434 }
435
436 /// Get the node type
437 pub fn get_type(&self) -> Option<NodeType> {
438 NodeType::from_int(xmlGetNodeType(self.node_ptr()))
439 }
440
441 /// Add a previous sibling
442 pub fn add_prev_sibling(
443 &mut self,
444 new_sibling: &mut Node,
445 ) -> Result<(), Box<dyn Error + Send + Sync>> {
446 new_sibling.set_linked();
447 unsafe {
448 if xmlAddPrevSibling(self.node_ptr_mut()?, new_sibling.node_ptr_mut()?).is_null() {
449 Err(From::from("add_prev_sibling returned NULL"))
450 } else {
451 Ok(())
452 }
453 }
454 }
455
456 /// Add a next sibling
457 pub fn add_next_sibling(
458 &mut self,
459 new_sibling: &mut Node,
460 ) -> Result<(), Box<dyn Error + Send + Sync>> {
461 new_sibling.set_linked();
462 unsafe {
463 if xmlAddNextSibling(self.node_ptr_mut()?, new_sibling.node_ptr_mut()?).is_null() {
464 Err(From::from("add_next_sibling returned NULL"))
465 } else {
466 Ok(())
467 }
468 }
469 }
470
471 /// Returns true if it is a text node
472 pub fn is_text_node(&self) -> bool {
473 self.get_type() == Some(NodeType::TextNode)
474 }
475
476 /// Checks if the given node is an Element
477 pub fn is_element_node(&self) -> bool {
478 self.get_type() == Some(NodeType::ElementNode)
479 }
480
481 /// Checks if the underlying libxml2 pointer is `NULL`
482 pub fn is_null(&self) -> bool {
483 self.node_ptr().is_null()
484 }
485
486 /// Returns the name of the node (empty string if name pointer is `NULL`)
487 pub fn get_name(&self) -> String {
488 let name_ptr = xmlNodeGetName(self.node_ptr());
489 if name_ptr.is_null() {
490 return String::new();
491 } //empty string
492 let c_string = unsafe { CStr::from_ptr(name_ptr) };
493 c_string.to_string_lossy().into_owned()
494 }
495
496 /// Sets the name of this `Node`
497 pub fn set_name(&mut self, name: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
498 let c_name = CString::new(name).unwrap();
499 unsafe { xmlNodeSetName(self.node_ptr_mut()?, c_name.as_bytes().as_ptr()) }
500 Ok(())
501 }
502
503 /// Returns the content of the node
504 /// (assumes UTF-8 XML document)
505 pub fn get_content(&self) -> String {
506 let content_ptr = unsafe { xmlNodeGetContent(self.node_ptr()) };
507 if content_ptr.is_null() {
508 //empty string when none
509 return String::new();
510 }
511 let c_string = unsafe { CStr::from_ptr(content_ptr as *const c_char) };
512 let rust_utf8 = c_string.to_string_lossy().into_owned();
513 bindgenFree(content_ptr as *mut c_void);
514 rust_utf8
515 }
516
517 /// Sets the text content of this `Node`
518 pub fn set_content(&mut self, content: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
519 let c_content = CString::new(content).unwrap();
520 unsafe { xmlNodeSetContent(self.node_ptr_mut()?, c_content.as_bytes().as_ptr()); }
521 Ok(())
522 }
523
524 /// Returns the value of property `name`
525 pub fn get_property(&self, name: &str) -> Option<String> {
526 let c_name = CString::new(name).unwrap();
527 let value_ptr = unsafe { xmlGetProp(self.node_ptr(), c_name.as_bytes().as_ptr()) };
528 if value_ptr.is_null() {
529 return None;
530 }
531 let c_value_string = unsafe { CStr::from_ptr(value_ptr as *const c_char) };
532 let prop_str = c_value_string.to_string_lossy().into_owned();
533 bindgenFree(value_ptr as *mut c_void);
534 Some(prop_str)
535 }
536
537 /// Returns the value of property `name` in namespace `ns`
538 pub fn get_property_ns(&self, name: &str, ns: &str) -> Option<String> {
539 let c_name = CString::new(name).unwrap();
540 let c_ns = CString::new(ns).unwrap();
541 let value_ptr = unsafe {
542 xmlGetNsProp(
543 self.node_ptr(),
544 c_name.as_bytes().as_ptr(),
545 c_ns.as_bytes().as_ptr(),
546 )
547 };
548 if value_ptr.is_null() {
549 return None;
550 }
551 let c_value_string = unsafe { CStr::from_ptr(value_ptr as *const c_char) };
552 let prop_str = c_value_string.to_string_lossy().into_owned();
553 bindgenFree(value_ptr as *mut c_void);
554 Some(prop_str)
555 }
556
557 /// Returns the value of property `name` with no namespace
558 pub fn get_property_no_ns(&self, name: &str) -> Option<String> {
559 let c_name = CString::new(name).unwrap();
560 let value_ptr = unsafe { xmlGetNoNsProp(self.node_ptr(), c_name.as_bytes().as_ptr()) };
561 if value_ptr.is_null() {
562 return None;
563 }
564 let c_value_string = unsafe { CStr::from_ptr(value_ptr as *const c_char) };
565 let prop_str = c_value_string.to_string_lossy().into_owned();
566 bindgenFree(value_ptr as *mut c_void);
567 Some(prop_str)
568 }
569
570 /// Return an attribute as a `Node` struct of type AttributeNode
571 pub fn get_property_node(&self, name: &str) -> Option<Node> {
572 let c_name = CString::new(name).unwrap();
573 unsafe {
574 let attr_node = xmlHasProp(self.node_ptr(), c_name.as_bytes().as_ptr());
575 self.ptr_as_option(attr_node as xmlNodePtr)
576 }
577 }
578
579 /// Return an attribute in a namespace `ns` as a `Node` of type AttributeNode
580 pub fn get_property_node_ns(&self, name: &str, ns: &str) -> Option<Node> {
581 let c_name = CString::new(name).unwrap();
582 let c_ns = CString::new(ns).unwrap();
583 let attr_node = unsafe {
584 xmlHasNsProp(
585 self.node_ptr(),
586 c_name.as_bytes().as_ptr(),
587 c_ns.as_bytes().as_ptr(),
588 )
589 };
590 self.ptr_as_option(attr_node as xmlNodePtr)
591 }
592
593 /// Return an attribute with no namespace as a `Node` of type AttributeNode
594 pub fn get_property_node_no_ns(&self, name: &str) -> Option<Node> {
595 let c_name = CString::new(name).unwrap();
596 let attr_node =
597 unsafe { xmlHasNsProp(self.node_ptr(), c_name.as_bytes().as_ptr(), ptr::null()) };
598 self.ptr_as_option(attr_node as xmlNodePtr)
599 }
600
601 /// Check if a property has been defined, without allocating its value
602 pub fn has_property(&self, name: &str) -> bool {
603 let c_name = CString::new(name).unwrap();
604 let value_ptr = unsafe { xmlHasProp(self.node_ptr(), c_name.as_bytes().as_ptr()) };
605 !value_ptr.is_null()
606 }
607
608 /// Check if property `name` in namespace `ns` exists
609 pub fn has_property_ns(&self, name: &str, ns: &str) -> bool {
610 let c_name = CString::new(name).unwrap();
611 let c_ns = CString::new(ns).unwrap();
612 let value_ptr = unsafe {
613 xmlHasNsProp(
614 self.node_ptr(),
615 c_name.as_bytes().as_ptr(),
616 c_ns.as_bytes().as_ptr(),
617 )
618 };
619 !value_ptr.is_null()
620 }
621
622 /// Check if property `name` with no namespace exists
623 pub fn has_property_no_ns(&self, name: &str) -> bool {
624 let c_name = CString::new(name).unwrap();
625 let value_ptr =
626 unsafe { xmlHasNsProp(self.node_ptr(), c_name.as_bytes().as_ptr(), ptr::null()) };
627 !value_ptr.is_null()
628 }
629
630 /// Alias for has_property
631 pub fn has_attribute(&self, name: &str) -> bool {
632 self.has_property(name)
633 }
634 /// Alias for has_property_ns
635 pub fn has_attribute_ns(&self, name: &str, ns: &str) -> bool {
636 self.has_property_ns(name, ns)
637 }
638
639 /// Alias for has_property_no_ns
640 pub fn has_attribute_no_ns(&self, name: &str) -> bool {
641 self.has_property_no_ns(name)
642 }
643
644 /// Sets the value of property `name` to `value`
645 pub fn set_property(
646 &mut self,
647 name: &str,
648 value: &str,
649 ) -> Result<(), Box<dyn Error + Send + Sync>> {
650 let c_name = CString::new(name).unwrap();
651 let c_value = CString::new(value).unwrap();
652 unsafe {
653 xmlSetProp(
654 self.node_ptr_mut()?,
655 c_name.as_bytes().as_ptr(),
656 c_value.as_bytes().as_ptr(),
657 )
658 };
659 Ok(())
660 }
661 /// Sets a namespaced attribute
662 pub fn set_property_ns(
663 &mut self,
664 name: &str,
665 value: &str,
666 ns: &Namespace,
667 ) -> Result<(), Box<dyn Error + Send + Sync>> {
668 let c_name = CString::new(name).unwrap();
669 let c_value = CString::new(value).unwrap();
670 unsafe {
671 xmlSetNsProp(
672 self.node_ptr_mut()?,
673 ns.ns_ptr(),
674 c_name.as_bytes().as_ptr(),
675 c_value.as_bytes().as_ptr(),
676 )
677 };
678 Ok(())
679 }
680
681 /// Removes the property of given `name`
682 pub fn remove_property(&mut self, name: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
683 let c_name = CString::new(name).unwrap();
684 unsafe {
685 let attr_node = xmlHasProp(self.node_ptr_mut()?, c_name.as_bytes().as_ptr());
686 if !attr_node.is_null() {
687 let remove_prop_status = xmlRemoveProp(attr_node);
688 if remove_prop_status == 0 {
689 Ok(())
690 } else {
691 // Propagate libxml2 failure to remove
692 Err(From::from(format!(
693 "libxml2 failed to remove property with status: {remove_prop_status:?}")))
694 }
695 } else {
696 // silently no-op if asked to remove a property which is not present
697 Ok(())
698 }
699 }
700 }
701
702 /// Removes the property of given `name` and namespace (`ns`)
703 pub fn remove_property_ns(
704 &mut self,
705 name: &str,
706 ns: &str,
707 ) -> Result<(), Box<dyn Error + Send + Sync>> {
708 let c_name = CString::new(name).unwrap();
709 let c_ns = CString::new(ns).unwrap();
710 unsafe {
711 let attr_node = xmlHasNsProp(
712 self.node_ptr_mut()?,
713 c_name.as_bytes().as_ptr(),
714 c_ns.as_bytes().as_ptr(),
715 );
716 if !attr_node.is_null() {
717 let remove_prop_status = xmlRemoveProp(attr_node);
718 if remove_prop_status == 0 {
719 Ok(())
720 } else {
721 // Propagate libxml2 failure to remove
722 Err(From::from(format!(
723 "libxml2 failed to remove property with status: {remove_prop_status:?}")))
724 }
725 } else {
726 // silently no-op if asked to remove a property which is not present
727 Ok(())
728 }
729 }
730 }
731
732 /// Removes the property of given `name` with no namespace
733 pub fn remove_property_no_ns(&mut self, name: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
734 let c_name = CString::new(name).unwrap();
735 let attr_node = unsafe {
736 xmlHasNsProp(
737 self.node_ptr_mut()?,
738 c_name.as_bytes().as_ptr(),
739 ptr::null(),
740 )
741 };
742 if !attr_node.is_null() {
743 let remove_prop_status = unsafe { xmlRemoveProp(attr_node) };
744 if remove_prop_status == 0 {
745 Ok(())
746 } else {
747 // Propagate libxml2 failure to remove
748 Err(From::from(format!(
749 "libxml2 failed to remove property with status: {remove_prop_status:?}")))
750 }
751 } else {
752 // silently no-op if asked to remove a property which is not present
753 Ok(())
754 }
755 }
756
757 /// Alias for get_property
758 pub fn get_attribute(&self, name: &str) -> Option<String> {
759 self.get_property(name)
760 }
761
762 /// Alias for get_property_ns
763 pub fn get_attribute_ns(&self, name: &str, ns: &str) -> Option<String> {
764 self.get_property_ns(name, ns)
765 }
766
767 /// Alias for get_property_no_ns
768 pub fn get_attribute_no_ns(&self, name: &str) -> Option<String> {
769 self.get_property_no_ns(name)
770 }
771
772 /// Alias for get_property_node
773 pub fn get_attribute_node(&self, name: &str) -> Option<Node> {
774 self.get_property_node(name)
775 }
776
777 /// Alias for get_property_node_ns
778 pub fn get_attribute_node_ns(&self, name: &str, ns: &str) -> Option<Node> {
779 self.get_property_node_ns(name, ns)
780 }
781
782 /// Alias for get_property_node_no_ns
783 pub fn get_attribute_node_no_ns(&self, name: &str) -> Option<Node> {
784 self.get_property_node_no_ns(name)
785 }
786
787 /// Alias for set_property
788 pub fn set_attribute(
789 &mut self,
790 name: &str,
791 value: &str,
792 ) -> Result<(), Box<dyn Error + Send + Sync>> {
793 self.set_property(name, value)
794 }
795 /// Alias for set_property_ns
796 pub fn set_attribute_ns(
797 &mut self,
798 name: &str,
799 value: &str,
800 ns: &Namespace,
801 ) -> Result<(), Box<dyn Error + Send + Sync>> {
802 self.set_property_ns(name, value, ns)
803 }
804
805 /// Alias for remove_property
806 pub fn remove_attribute(&mut self, name: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
807 self.remove_property(name)
808 }
809
810 /// Alias for remove_property_ns
811 pub fn remove_attribute_ns(
812 &mut self,
813 name: &str,
814 ns: &str,
815 ) -> Result<(), Box<dyn Error + Send + Sync>> {
816 self.remove_property_ns(name, ns)
817 }
818
819 /// Alias for remove_property_no_ns
820 pub fn remove_attribute_no_ns(&mut self, name: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
821 self.remove_property_no_ns(name)
822 }
823
824 /// Get a copy of the attributes of this node
825 pub fn get_properties(&self) -> HashMap<String, String> {
826 let mut attributes = HashMap::new();
827
828 let mut current_prop = xmlGetFirstProperty(self.node_ptr());
829 while !current_prop.is_null() {
830 let name_ptr = xmlAttrName(current_prop);
831 let c_name_string = unsafe { CStr::from_ptr(name_ptr) };
832 let name = c_name_string.to_string_lossy().into_owned();
833 let value = self.get_property(&name).unwrap_or_default();
834 attributes.insert(name, value);
835 current_prop = xmlNextPropertySibling(current_prop);
836 }
837
838 attributes
839 }
840
841 /// Get a copy of this node's attributes and their namespaces
842 pub fn get_properties_ns(&self) -> HashMap<(String, Option<Namespace>), String> {
843 let mut attributes = HashMap::new();
844
845 let mut current_prop = xmlGetFirstProperty(self.node_ptr());
846 while !current_prop.is_null() {
847 let name_ptr = xmlAttrName(current_prop);
848 let c_name_string = unsafe { CStr::from_ptr(name_ptr) };
849 let name = c_name_string.to_string_lossy().into_owned();
850 let ns_ptr = xmlAttrNs(current_prop);
851 if ns_ptr.is_null() {
852 let value = self.get_property_no_ns(&name).unwrap_or_default();
853 attributes.insert((name, None), value);
854 } else {
855 let ns = Namespace { ns_ptr };
856 let value = self
857 .get_property_ns(&name, &ns.get_href())
858 .unwrap_or_default();
859 attributes.insert((name, Some(ns)), value);
860 }
861 current_prop = xmlNextPropertySibling(current_prop);
862 }
863
864 attributes
865 }
866
867 /// Alias for `get_properties`
868 pub fn get_attributes(&self) -> HashMap<String, String> {
869 self.get_properties()
870 }
871
872 /// Alias for `get_properties_ns`
873 pub fn get_attributes_ns(&self) -> HashMap<(String, Option<Namespace>), String> {
874 self.get_properties_ns()
875 }
876
877 /// Gets the active namespace associated of this node
878 pub fn get_namespace(&self) -> Option<Namespace> {
879 let ns_ptr = xmlNodeNs(self.node_ptr());
880 if ns_ptr.is_null() {
881 None
882 } else {
883 Some(Namespace { ns_ptr })
884 }
885 }
886
887 /// Gets a list of namespaces associated with this node
888 pub fn get_namespaces(&self, doc: &Document) -> Vec<Namespace> {
889 let list_ptr_raw = unsafe { xmlGetNsList(doc.doc_ptr(), self.node_ptr()) };
890 if list_ptr_raw.is_null() {
891 Vec::new()
892 } else {
893 let mut namespaces = Vec::new();
894 let mut ptr_iter = list_ptr_raw as *mut xmlNsPtr;
895 unsafe {
896 while !ptr_iter.is_null() && !(*ptr_iter).is_null() {
897 namespaces.push(Namespace { ns_ptr: *ptr_iter });
898 ptr_iter = ptr_iter.add(1);
899 }
900 /* TODO: valgrind suggests this technique isn't sufficiently fluent:
901 ==114895== Conditional jump or move depends on uninitialised value(s)
902 ==114895== at 0x4E9962F: xmlFreeNs (in /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.4)
903 ==114895== by 0x195CE8: libxml::tree::Node::get_namespaces (tree.rs:723)
904 ==114895== by 0x12E7B6: base_tests::can_work_with_namespaces (base_tests.rs:537)
905
906 DG: I could not improve on this state without creating memory leaks after ~1 hour, so I am
907 marking it as future work.
908 */
909 /* TODO: How do we properly deallocate here? The approach bellow reliably segfaults tree_tests on 1 thread */
910 // println!("\n-- xmlfreens on : {:?}", list_ptr_raw);
911 // xmlFreeNs(list_ptr_raw as xmlNsPtr);
912 }
913 namespaces
914 }
915 }
916
917 /// Get a list of namespaces declared with this node
918 pub fn get_namespace_declarations(&self) -> Vec<Namespace> {
919 if self.get_type() != Some(NodeType::ElementNode) {
920 // only element nodes can have declarations
921 return Vec::new();
922 }
923 let mut namespaces = Vec::new();
924 let mut ns_ptr = xmlNodeNsDeclarations(self.node_ptr());
925 while !ns_ptr.is_null() {
926 if !xmlNsPrefix(ns_ptr).is_null() || !xmlNsHref(ns_ptr).is_null() {
927 namespaces.push(Namespace { ns_ptr });
928 }
929 ns_ptr = xmlNextNsSibling(ns_ptr);
930 }
931 namespaces
932 }
933
934 /// Sets a `Namespace` for the node
935 pub fn set_namespace(
936 &mut self,
937 namespace: &Namespace,
938 ) -> Result<(), Box<dyn Error + Send + Sync>> {
939 unsafe {
940 xmlSetNs(self.node_ptr_mut()?, namespace.ns_ptr());
941 }
942 Ok(())
943 }
944
945 /// Looks up the prefix of a namespace from its URI, basedo around a given `Node`
946 pub fn lookup_namespace_prefix(&self, href: &str) -> Option<String> {
947 if href.is_empty() {
948 return None;
949 }
950 let c_href = CString::new(href).unwrap();
951 unsafe {
952 let ptr_mut = self.node_ptr();
953 let ns_ptr = xmlSearchNsByHref(xmlGetDoc(ptr_mut), ptr_mut, c_href.as_bytes().as_ptr());
954 if !ns_ptr.is_null() {
955 let ns = Namespace { ns_ptr };
956 let ns_prefix = ns.get_prefix();
957 Some(ns_prefix)
958 } else {
959 None
960 }
961 }
962 }
963
964 /// Looks up the uri of a namespace from its prefix, basedo around a given `Node`
965 pub fn lookup_namespace_uri(&self, prefix: &str) -> Option<String> {
966 if prefix.is_empty() {
967 return None;
968 }
969 let c_prefix = CString::new(prefix).unwrap();
970 unsafe {
971 let ns_ptr = xmlSearchNs(
972 xmlGetDoc(self.node_ptr()),
973 self.node_ptr(),
974 c_prefix.as_bytes().as_ptr(),
975 );
976 if !ns_ptr.is_null() {
977 let ns = Namespace { ns_ptr };
978 let ns_prefix = ns.get_href();
979 if !ns_prefix.is_empty() {
980 Some(ns_prefix)
981 } else {
982 None
983 }
984 } else {
985 None
986 }
987 }
988 }
989
990 // TODO: Clear a future Document namespaces vec
991 /// Removes the namespaces of this `Node` and it's children!
992 pub fn recursively_remove_namespaces(&mut self) -> Result<(), Box<dyn Error + Send + Sync>> {
993 xmlNodeRecursivelyRemoveNs(self.node_ptr_mut()?);
994 Ok(())
995 }
996
997 /// Get a set of class names from this node's attributes
998 pub fn get_class_names(&self) -> HashSet<String> {
999 let mut set = HashSet::new();
1000 if let Some(value) = self.get_property("class") {
1001 for n in value.split(' ') {
1002 set.insert(n.to_owned());
1003 }
1004 }
1005 set
1006 }
1007
1008 /// Creates a new `Node` as child to the self `Node`
1009 pub fn add_child(&mut self, child: &mut Node) -> Result<(), String> {
1010 child.set_linked();
1011 unsafe {
1012 let new_child_ptr = xmlAddChild(self.node_ptr_mut()?, child.node_ptr_mut()?);
1013 if new_child_ptr.is_null() {
1014 Err("add_child encountered NULL pointer".to_string())
1015 } else {
1016 Ok(())
1017 }
1018 }
1019 }
1020
1021 /// Creates a new `Node` as child to the self `Node`
1022 pub fn new_child(
1023 &mut self,
1024 ns: Option<Namespace>,
1025 name: &str,
1026 ) -> Result<Node, Box<dyn Error + Send + Sync>> {
1027 let c_name = CString::new(name).unwrap();
1028 let ns_ptr = match ns {
1029 None => ptr::null_mut(),
1030 Some(mut ns) => ns.ns_ptr_mut(),
1031 };
1032 unsafe {
1033 let new_ptr = xmlNewChild(
1034 self.node_ptr_mut()?,
1035 ns_ptr,
1036 c_name.as_bytes().as_ptr(),
1037 ptr::null(),
1038 );
1039 Ok(Node::wrap(new_ptr, &self.get_docref().upgrade().unwrap()))
1040 }
1041 }
1042
1043 /// Adds a new text child, to this `Node`
1044 pub fn add_text_child(
1045 &mut self,
1046 ns: Option<Namespace>,
1047 name: &str,
1048 content: &str,
1049 ) -> Result<Node, Box<dyn Error + Send + Sync>> {
1050 let c_name = CString::new(name).unwrap();
1051 let c_content = CString::new(content).unwrap();
1052 let ns_ptr = match ns {
1053 None => ptr::null_mut(),
1054 Some(mut ns) => ns.ns_ptr_mut(),
1055 };
1056 unsafe {
1057 let new_ptr = xmlNewTextChild(
1058 self.node_ptr_mut()?,
1059 ns_ptr,
1060 c_name.as_bytes().as_ptr(),
1061 c_content.as_bytes().as_ptr(),
1062 );
1063 Ok(Node::wrap(new_ptr, &self.get_docref().upgrade().unwrap()))
1064 }
1065 }
1066
1067 /// Append text to this `Node`
1068 pub fn append_text(&mut self, content: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
1069 let c_len = content.len() as i32;
1070 if c_len > 0 {
1071 let c_content = CString::new(content).unwrap();
1072 unsafe {
1073 xmlNodeAddContentLen(self.node_ptr_mut()?, c_content.as_bytes().as_ptr(), c_len);
1074 }
1075 }
1076 Ok(())
1077 }
1078
1079 /// Unbinds the Node from its siblings and Parent, but not from the Document it belongs to.
1080 ///
1081 /// At the libxml2 level, `xmlUnlinkNode` severs `parent`/`prev`/`next`
1082 /// links but **leaves `node->doc` set** — the source document is
1083 /// still recorded as the lifetime owner of the underlying allocation.
1084 /// Consequences for subsequent handling:
1085 ///
1086 /// * **Re-attach** the node into a tree (via `add_child`,
1087 /// `add_prev_sibling`, `add_next_sibling`, or
1088 /// `Document::set_root_element`). Lifetime stays with the source
1089 /// document; nothing more to do.
1090 /// * **Copy it out** into a new document via
1091 /// [`Document::dup_node_into_new_doc`] (or a comparable libxml2
1092 /// path). The copy is independent; the original is still detached.
1093 /// * **Discard the original**: call [`Node::set_rust_owned`] on it.
1094 /// The wrapper's `Drop` will then `xmlFreeNode` the C subtree when
1095 /// the last clone drops. Without this call, the detached subtree
1096 /// leaks: the wrapper's `Drop` is a no-op (it must be, to avoid
1097 /// freeing memory the source document still considers live), and
1098 /// the source document's eventual `xmlFreeDoc` walks the tree
1099 /// topology, so it never reaches a parent==NULL subtree.
1100 ///
1101 /// In short: an unlinked node that is *neither* re-attached *nor*
1102 /// marked `set_rust_owned` is a leak until process exit.
1103 pub fn unlink_node(&mut self) {
1104 let node_type = self.get_type();
1105 if node_type != Some(NodeType::DocumentNode)
1106 && node_type != Some(NodeType::DocumentFragNode)
1107 && !self.is_unlinked()
1108 {
1109 // only unlink nodes that are currently marked as linked
1110 self.set_unlinked();
1111 unsafe {
1112 xmlUnlinkNode(self.node_ptr());
1113 }
1114 }
1115 }
1116 /// Alias for `unlink_node`
1117 pub fn unlink(&mut self) {
1118 self.unlink_node()
1119 }
1120 /// Alias for `unlink_node`
1121 pub fn unbind_node(&mut self) {
1122 self.unlink_node()
1123 }
1124 /// Alias for `unlink_node`
1125 pub fn unbind(&mut self) {
1126 self.unlink_node()
1127 }
1128
1129 /// Checks if node is marked as unlinked
1130 ///
1131 /// Returns `true` for both `Unlinked` and `RustOwned` states — both
1132 /// are detached from any document tree.
1133 pub fn is_unlinked(&self) -> bool {
1134 !matches!(self.0.borrow().linkage, Linkage::Linked)
1135 }
1136
1137 /// Take ownership of this detached node's C allocation.
1138 ///
1139 /// After this call, the C node will be freed via `xmlFreeNode` when the
1140 /// last `Node` clone drops, regardless of whether `node->doc` is still
1141 /// set. The flag is sticky and propagates to every clone (they share
1142 /// the same `_Node`), so transferring ownership once is sufficient.
1143 ///
1144 /// Use this on a subtree that has been:
1145 /// 1. detached from its parent via `unlink_node`, AND
1146 /// 2. either copied out into another document (e.g. via
1147 /// `Document::dup_node_into_new_doc`) or otherwise will not be
1148 /// re-attached to any tree.
1149 ///
1150 /// Without this call, detached nodes are *not* freed by the wrapper —
1151 /// they remain attributed to `node->doc` for safety, and `xmlFreeDoc`
1152 /// reclaims them only if they're still reachable from the doc root.
1153 /// A subtree that has been unlinked but not re-attached and not marked
1154 /// rust-owned will leak until process exit.
1155 ///
1156 /// # Safety preconditions
1157 ///
1158 /// Calling this on a node that is still `Linked` (part of a document
1159 /// tree) is **undefined behavior**: the node's later free will leave
1160 /// dangling pointers in its former parent / siblings / ID table. The
1161 /// wrapper cannot cheaply verify this, so the caller must guarantee
1162 /// it. In debug builds we panic if the precondition is obviously
1163 /// violated.
1164 pub fn set_rust_owned(&self) {
1165 let mut inner = self.0.borrow_mut();
1166 debug_assert!(
1167 !matches!(inner.linkage, Linkage::Linked),
1168 "set_rust_owned called on a Linked node — call unlink_node first"
1169 );
1170 inner.linkage = Linkage::RustOwned;
1171 }
1172
1173 /// Returns whether the C allocation is owned by the Rust wrapper.
1174 /// See `set_rust_owned`.
1175 pub fn is_rust_owned(&self) -> bool {
1176 matches!(self.0.borrow().linkage, Linkage::RustOwned)
1177 }
1178
1179 fn ptr_as_option(&self, node_ptr: xmlNodePtr) -> Option<Node> {
1180 if node_ptr.is_null() {
1181 None
1182 } else {
1183 let doc_ref = self.get_docref().upgrade().unwrap();
1184 let new_node = Node::wrap(node_ptr, &doc_ref);
1185 Some(new_node)
1186 }
1187 }
1188
1189 /// internal helper to ensure the node is marked as linked/imported/adopted in the main document tree.
1190 ///
1191 /// Transitions from `Unlinked` to `Linked`. If the node is already
1192 /// `RustOwned`, this is a no-op in release builds and a debug-assert
1193 /// failure in debug builds: the caller has explicitly taken ownership
1194 /// and re-linking it would set up a guaranteed double-free
1195 /// (the new parent's `xmlFreeDoc` will free the subtree, then this
1196 /// wrapper's `Drop` will free it again). There is no public path to
1197 /// untake ownership; the right fix is for the caller to never re-link
1198 /// a `RustOwned` node.
1199 pub(crate) fn set_linked(&self) {
1200 let mut inner = self.0.borrow_mut();
1201 debug_assert!(
1202 !matches!(inner.linkage, Linkage::RustOwned),
1203 "set_linked called on a RustOwned node — re-linking would set up a double free; \
1204 drop the wrapper before re-attaching, or do not call set_rust_owned"
1205 );
1206 if matches!(inner.linkage, Linkage::Unlinked) {
1207 inner.linkage = Linkage::Linked;
1208 }
1209 }
1210
1211 /// internal helper to ensure the node is marked as unlinked/removed from the main document tree.
1212 ///
1213 /// Transitions from `Linked` to `Unlinked`. Leaves `RustOwned`
1214 /// untouched — that variant already implies "detached".
1215 pub(crate) fn set_unlinked(&self) {
1216 {
1217 let mut inner = self.0.borrow_mut();
1218 if matches!(inner.linkage, Linkage::Linked) {
1219 inner.linkage = Linkage::Unlinked;
1220 }
1221 }
1222 self
1223 .get_docref()
1224 .upgrade()
1225 .unwrap()
1226 .borrow_mut()
1227 .forget_node(self.node_ptr());
1228 }
1229
1230 /// find nodes via xpath, at a specified node or the document root
1231 pub fn findnodes(&self, xpath: &str) -> Result<Vec<Node>, ()> {
1232 let mut context = Context::from_node(self)?;
1233 context.findnodes(xpath, Some(self))
1234 }
1235
1236 /// Search this node for XPath `path`, and return only the first match.
1237 pub fn at_xpath(&self, path: &str, ns_binlings: &[(&str, &str)]) -> Result<Option<Node>, ()> {
1238 let mut context = Context::from_node(self)?;
1239 for (prefix, href) in ns_binlings {
1240 context.register_namespace(prefix, href)?;
1241 }
1242 let nodes = context.findnodes(path, Some(self))?;
1243
1244 Ok(nodes.first().cloned())
1245 }
1246
1247 /// Get a list of ancestor Node for this Node.
1248 pub fn ancestors(&self) -> Vec<Node> {
1249 let node_ptr = self.node_ptr();
1250
1251 let mut res = Vec::new();
1252
1253 let ancestor_ptrs = node_ancestors(node_ptr);
1254
1255 for ptr in ancestor_ptrs {
1256 if let Some(node) = self.ptr_as_option(ptr) {
1257 res.push(node)
1258 }
1259 }
1260
1261 res
1262 }
1263
1264 /// find String values via xpath, at a specified node or the document root
1265 pub fn findvalues(&self, xpath: &str) -> Result<Vec<String>, ()> {
1266 let mut context = Context::from_node(self)?;
1267 context.findvalues(xpath, Some(self))
1268 }
1269
1270 /// replace a `self`'s `old` child node with a `new` node in the same position
1271 /// borrowed from Perl's XML::LibXML
1272 pub fn replace_child_node(
1273 &mut self,
1274 mut new: Node,
1275 mut old: Node,
1276 ) -> Result<Node, Box<dyn Error + Send + Sync>> {
1277 // if newNode == oldNode or self == newNode then do nothing, just return nNode.
1278 if new == old || self == &new {
1279 // nothing to do here, already in place
1280 Ok(old)
1281 } else if self.get_type() == Some(NodeType::ElementNode) {
1282 match old.get_parent() { Some(old_parent) => {
1283 if &old_parent == self {
1284 // unlink new to be available for insertion
1285 new.unlink();
1286 // mid-child case
1287 old.add_next_sibling(&mut new)?;
1288 old.unlink();
1289 Ok(old)
1290 } else {
1291 Err(From::from(format!(
1292 "Old node was not a child of {:?} parent. Registered parent is {:?} instead.",
1293 self.get_name(),
1294 old_parent.get_name()
1295 )))
1296 }
1297 } _ => {
1298 Err(From::from(format!(
1299 "Old node was not a child of {:?} parent. No registered parent exists.",
1300 self.get_name()
1301 )))
1302 }}
1303 } else {
1304 Err(From::from(
1305 "Can only call replace_child_node an a NodeType::Element type parent.",
1306 ))
1307 }
1308 }
1309 }
1310
1311 fn node_ancestors(node_ptr: xmlNodePtr) -> Vec<xmlNodePtr> {
1312 if node_ptr.is_null() {
1313 return Vec::new();
1314 }
1315
1316 let mut parent_ptr = xmlGetParent(node_ptr);
1317
1318 if parent_ptr.is_null() {
1319 Vec::new()
1320 } else {
1321 let mut parents = vec![parent_ptr];
1322
1323 while !xmlGetParent(parent_ptr).is_null() {
1324 parent_ptr = xmlGetParent(parent_ptr);
1325 parents.push(parent_ptr);
1326 }
1327
1328 parents
1329 }
1330 }
1331
1332 mod c14n;