Class: Moxml::Adapter::Libxml

Inherits:
Base
  • Object
show all
Extended by:
Serialize
Defined in:
lib/moxml/adapter/libxml.rb,
lib/moxml/adapter/libxml/serialize.rb,
lib/moxml/adapter/libxml/entity_ref_registry.rb

Defined Under Namespace

Modules: Serialize Classes: DoctypeWrapper, EntityRefRegistry, LibXMLSAXBridge

Class Method Summary collapse

Methods included from Serialize

blank_content?, blank_text_node?, collect_non_blank_children, emit_attributes, emit_children_with_layout, emit_eref_interleaved_children, emit_namespace_definitions, format_ns_declaration, lookup_entity_ref_serialization, native_root_output, parent_namespace_defs, serialize, serialize_child_to_xml, serialize_element, serialize_element_with_namespaces, serialize_node

Methods inherited from Base

attribute_name, bulk_materialize?, create_cdata, create_comment, create_declaration, create_doctype, create_element, create_entity_reference, create_namespace, create_processing_instruction, create_text, decode_entities, entity_bearing?, free_document, in_scope_namespaces, materialize_fields, parse_errors, preprocess_entities, restore_entities, sax_supported?, set_attribute_value

Methods included from XmlUtils

#encode_entities, #normalize_xml_value, #validate_comment_content, #validate_declaration_encoding, #validate_declaration_standalone, #validate_declaration_version, #validate_element_name, #validate_entity_reference_name, #validate_pi_target, #validate_prefix, #validate_uri

Class Method Details

.actual_native(child_native, parent_native) ⇒ Object

LibXML's doc.root= creates a new Ruby wrapper with different object_id. Return the actual root node so attachments are stored on the correct object.



1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/moxml/adapter/libxml.rb', line 1061

def actual_native(child_native, parent_native)
  if parent_native.is_a?(::LibXML::XML::Document)
    pending = attachments.get(parent_native, :_pending_root_refresh)
    if pending && pending == child_native.object_id
      attachments.delete(parent_native, :_pending_root_refresh)
      return parent_native.root
    end
  end
  child_native
end

.add_child(element, child) ⇒ Object



576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/moxml/adapter/libxml.rb', line 576

def add_child(element, child)
  return unless element && child

  # Unwrap both element and child
  native_elem = unpatch_node(element)
  native_child = unpatch_node(child)

  # EntityReference wrappers can't go in LibXML's native tree.
  # Store them on the document for interleaved serialization.
  if child.is_a?(CustomizedLibxml::EntityReference)
    doc = native_elem.is_a?(::LibXML::XML::Document) ? native_elem : native_elem.doc
    entity_ref_registry(doc).register(native_elem, child)
    return
  end

  # For LibXML: if parent has a DEFAULT namespace (nil/empty prefix) and child is an element without a namespace,
  # explicitly set the child's namespace to match the parent's for XPath compatibility
  # NOTE: Prefixed namespaces are NOT inherited, only default namespaces.
  #
  # Reorder cheap-first: skip the expensive `.namespaces` fetches
  # entirely for non-element children (text, comment, cdata, PI),
  # which is roughly 30-50% of adds in a typical doc.
  if native_child.is_a?(::LibXML::XML::Node) && native_child.element? &&
      native_elem.is_a?(::LibXML::XML::Node) && native_elem.namespaces&.namespace &&
      (!native_child.namespaces.namespace || native_child.namespaces.namespace.href.to_s.empty?)

    parent_ns = native_elem.namespaces.namespace
    # Only set child's namespace if parent's namespace is DEFAULT (nil or empty prefix)
    if parent_ns.prefix.nil? || parent_ns.prefix.to_s.empty?
      native_child.namespaces.namespace = parent_ns
    end
  end

  if native_elem.is_a?(::LibXML::XML::Document)
    # For Declaration wrappers, store them for serialization
    if child.is_a?(CustomizedLibxml::Declaration)
      attachments.set(native_elem, :declaration, child)
      # Also store reference to parent document in the declaration
      child.parent_doc = native_elem
      return
    end

    # For DOCTYPE wrappers, store them for serialization
    if child.is_a?(DoctypeWrapper)
      attachments.set(native_elem, :doctype, child)
      return
    end

    # For document-level PIs, store them for serialization
    if child.is_a?(CustomizedLibxml::ProcessingInstruction)
      pis = attachments.get(native_elem, :pis) || []
      pis << child
      attachments.set(native_elem, :pis, pis)
      return
    end

    # For text nodes added to document, store them for serialization
    # Documents can't have text children in LibXML
    if child.is_a?(CustomizedLibxml::Text)
      texts = attachments.get(native_elem, :texts) || []
      texts << child
      attachments.set(native_elem, :texts, texts)
      return
    end

    # For documents, check if adding the first root element
    if native_elem.root.nil? && node_type(native_child) == :element
      # Set as root element
      native_elem.root = native_child
      # Flag for actual_native to refresh the wrapper's native reference
      attachments.set(native_elem, :_pending_root_refresh,
                      native_child.object_id)
    elsif native_elem.root
      # Document has root, add to it instead
      import_and_add(native_elem.doc, native_elem.root, native_child)
    end
  else
    import_and_add(native_elem.doc, native_elem, native_child)
    doc = native_elem.doc || native_elem
    entity_ref_registry(doc).append_native(native_elem)
  end
end

.add_next_sibling(node, sibling) ⇒ Object



685
686
687
688
689
690
691
# File 'lib/moxml/adapter/libxml.rb', line 685

def add_next_sibling(node, sibling)
  return unless node && sibling

  native_node = unpatch_node(node)
  native_sibling = unpatch_node(sibling)
  native_node.next = native_sibling
end

.add_previous_sibling(node, sibling) ⇒ Object



665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/moxml/adapter/libxml.rb', line 665

def add_previous_sibling(node, sibling)
  return unless node && sibling

  native_node = unpatch_node(node)
  native_sibling = unpatch_node(sibling)

  # Special handling for document-level processing instructions
  # When adding a PI as sibling to root element, store it on document
  if sibling.is_a?(CustomizedLibxml::ProcessingInstruction) &&
      native_node.is_a?(::LibXML::XML::Node) && native_node.doc
    doc = native_node.doc
    pis = attachments.get(doc, :pis) || []
    pis << sibling
    attachments.set(doc, :pis, pis)
    return
  end

  native_node.prev = native_sibling
end

.append_child_sequence(element, type) ⇒ Object



659
660
661
662
663
# File 'lib/moxml/adapter/libxml.rb', line 659

def append_child_sequence(element, type)
  seq = attachments.get(element, :child_sequence) || []
  seq << type
  attachments.set(element, :child_sequence, seq)
end

.at_xpath(node, expression, namespaces = nil) ⇒ Object



963
964
965
966
# File 'lib/moxml/adapter/libxml.rb', line 963

def at_xpath(node, expression, namespaces = nil)
  results = xpath(node, expression, namespaces)
  results&.first
end

.attachmentsObject



71
72
73
# File 'lib/moxml/adapter/libxml.rb', line 71

def attachments
  @attachments ||= Moxml::NativeAttachment.new
end

.attribute_element(attr) ⇒ Object



423
424
425
# File 'lib/moxml/adapter/libxml.rb', line 423

def attribute_element(attr)
  attr&.parent
end

.attribute_namespace(attr) ⇒ Object



427
428
429
430
431
432
# File 'lib/moxml/adapter/libxml.rb', line 427

def attribute_namespace(attr)
  return nil unless attr
  return nil unless attr.is_a?(::LibXML::XML::Attr)

  attr.ns
end

.attributes(element) ⇒ Object



408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/moxml/adapter/libxml.rb', line 408

def attributes(element)
  native_elem = unpatch_node(element)
  return [] unless native_elem
  unless native_elem.is_a?(::LibXML::XML::Node) && native_elem.element?
    return []
  end
  return [] unless native_elem.attributes?

  attrs = []
  native_elem.each_attr do |attr|
    attrs << attr unless attr.name.to_s.start_with?("xmlns")
  end
  attrs
end

.cdata_content(node) ⇒ Object



822
823
824
825
# File 'lib/moxml/adapter/libxml.rb', line 822

def cdata_content(node)
  # libxml stores CDATA payload verbatim; no decoding needed.
  unpatch_node(node)&.content
end

.children(node) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/moxml/adapter/libxml.rb', line 315

def children(node)
  native_node = unpatch_node(node)
  return [] unless native_node

  # Handle Document specially - it doesn't have children? method.
  # The binding's document chain lists prolog/epilog PIs and
  # comments around the root (Nokogiri-shaped contract); the
  # DOCTYPE attachment rides along first, mirroring the other
  # adapters.
  if native_node.is_a?(::LibXML::XML::Document)
    result = []
    has_native_doctype = false
    node = native_node.child
    while node
      has_native_doctype ||= node.node_type == ::LibXML::XML::Node::DTD_NODE
      result << patch_node(node)
      node = node.next
    end

    unless has_native_doctype
      doctype_wrapper = attachments.get(native_node, :doctype)
      result.unshift(doctype_wrapper) if doctype_wrapper
    end

    return result
  end

  result = []
  if native_node.children?
    native_node.each_child do |child|
      result << patch_node(child)
    end
  end

  # Include any EntityReference wrappers stored on the document
  doc = native_node.doc
  entity_refs = entity_ref_registry(doc).refs_for(native_node)
  result.concat(entity_refs) if entity_refs

  result
end

.comment_content(node) ⇒ Object



831
832
833
834
# File 'lib/moxml/adapter/libxml.rb', line 831

def comment_content(node)
  native_node = unpatch_node(node)
  native_node&.content
end

.create_document(_native_doc = nil) ⇒ Object



188
189
190
# File 'lib/moxml/adapter/libxml.rb', line 188

def create_document(_native_doc = nil)
  ::LibXML::XML::Document.new
end

.create_native_cdata(content, _owner_doc = nil) ⇒ Object



209
210
211
212
# File 'lib/moxml/adapter/libxml.rb', line 209

def create_native_cdata(content, _owner_doc = nil)
  native = ::LibXML::XML::Node.new_cdata(content.to_s)
  CustomizedLibxml::Cdata.new(native)
end

.create_native_comment(content, _owner_doc = nil) ⇒ Object



214
215
216
217
# File 'lib/moxml/adapter/libxml.rb', line 214

def create_native_comment(content, _owner_doc = nil)
  native = ::LibXML::XML::Node.new_comment(content.to_s)
  CustomizedLibxml::Comment.new(native)
end

.create_native_declaration(version, encoding, standalone) ⇒ Object



224
225
226
227
228
# File 'lib/moxml/adapter/libxml.rb', line 224

def create_native_declaration(version, encoding, standalone)
  doc = create_document
  # Return a Declaration wrapper with explicit parameters
  CustomizedLibxml::Declaration.new(doc, version, encoding, standalone)
end

.create_native_doctype(name, external_id, system_id) ⇒ Object



230
231
232
233
234
235
# File 'lib/moxml/adapter/libxml.rb', line 230

def create_native_doctype(name, external_id, system_id)
  # LibXML::XML::Dtd.new has bizarre parameter order, so we just
  # store values directly in our wrapper
  DoctypeWrapper.new(create_document, name.to_s, external_id&.to_s,
                     system_id&.to_s)
end

.create_native_element(name, _owner_doc = nil) ⇒ Object



192
193
194
# File 'lib/moxml/adapter/libxml.rb', line 192

def create_native_element(name, _owner_doc = nil)
  ::LibXML::XML::Node.new(name.to_s)
end

.create_native_entity_reference(name) ⇒ Object



201
202
203
# File 'lib/moxml/adapter/libxml.rb', line 201

def create_native_entity_reference(name)
  CustomizedLibxml::EntityReference.new(name)
end

.create_native_namespace(element, prefix, uri) ⇒ Object



860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'lib/moxml/adapter/libxml.rb', line 860

def create_native_namespace(element, prefix, uri)
  native_elem = unpatch_node(element)
  return nil unless native_elem

  ns = ::LibXML::XML::Namespace.new(
    native_elem,
    prefix.to_s.empty? ? nil : prefix.to_s,
    uri.to_s,
  )

  # For default namespace (nil/empty prefix), set it as the element's namespace
  native_elem.namespaces.namespace = ns if prefix.to_s.empty?

  ns
end

.create_native_processing_instruction(target, content) ⇒ Object



219
220
221
222
# File 'lib/moxml/adapter/libxml.rb', line 219

def create_native_processing_instruction(target, content)
  native = ::LibXML::XML::Node.new_pi(target.to_s, content.to_s)
  CustomizedLibxml::ProcessingInstruction.new(native)
end

.create_native_text(content, _owner_doc = nil) ⇒ Object



196
197
198
199
# File 'lib/moxml/adapter/libxml.rb', line 196

def create_native_text(content, _owner_doc = nil)
  native = ::LibXML::XML::Node.new_text(content.to_s)
  CustomizedLibxml::Text.new(native)
end

.declaration_attribute(node, name) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/moxml/adapter/libxml.rb', line 269

def declaration_attribute(node, name)
  return nil unless node

  # Handle Declaration wrapper
  if node.is_a?(CustomizedLibxml::Declaration)
    case name
    when "version"
      node.version
    when "encoding"
      node.encoding
    when "standalone"
      node.standalone # Returns "yes", "no", or nil
    end
  else
    # Fallback for native documents
    case name
    when "version"
      node.version
    when "encoding"
      enc = node.encoding
      enc ? encoding_to_string(enc) : nil
    when "standalone"
      node.standalone? ? "yes" : nil
    end
  end
end

.doctype_external_id(native) ⇒ Object



926
927
928
# File 'lib/moxml/adapter/libxml.rb', line 926

def doctype_external_id(native)
  native.external_id
end

.doctype_name(native) ⇒ Object

Doctype accessor methods



921
922
923
924
# File 'lib/moxml/adapter/libxml.rb', line 921

def doctype_name(native)
  # LibXML uses DoctypeWrapper which stores the values
  native.name
end

.doctype_system_id(native) ⇒ Object



930
931
932
# File 'lib/moxml/adapter/libxml.rb', line 930

def doctype_system_id(native)
  native.system_id
end

.document(node) ⇒ Object



387
388
389
390
391
392
393
394
395
396
# File 'lib/moxml/adapter/libxml.rb', line 387

def document(node)
  native_node = unpatch_node(node)
  return nil unless native_node

  # Handle documents themselves
  return native_node if native_node.is_a?(::LibXML::XML::Document)

  # For other nodes, return their document
  native_node.doc
end

.duplicate_node(node) ⇒ Object

Shallow duplication: copies the node itself (name, attrs, namespaces) but NOT its descendants (deep duplication composes this). walks the source tree and re-adds children one at a time via add_child, so a deep copy here would be done only to be stripped by replace_children, then rebuilt — O(N²) waste on parse.

For callers that need a true deep copy (e.g. the import_and_add fallback when LibXML can't move the subtree directly), use deep_duplicate_node.



977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/moxml/adapter/libxml.rb', line 977

def duplicate_node(node)
  return nil unless node

  native_node = unpatch_node(node)

  case node_type(node)
  when :doctype
    if node.is_a?(DoctypeWrapper)
      DoctypeWrapper.new(
        create_document,
        node.name,
        node.external_id,
        node.system_id,
      )
    else
      node
    end
  when :element
    # Public dup contract: a full deep copy of the subtree
    deep_duplicate_node(native_node)
  when :text
    ::LibXML::XML::Node.new_text(native_node.content)
  when :cdata
    ::LibXML::XML::Node.new_cdata(native_node.content)
  when :comment
    ::LibXML::XML::Node.new_comment(native_node.content)
  when :processing_instruction
    ::LibXML::XML::Node.new_pi(native_node.name, native_node.content)
  else
    native_node.dup
  end
end

.entity_reference_name(node) ⇒ Object



205
206
207
# File 'lib/moxml/adapter/libxml.rb', line 205

def entity_reference_name(node)
  node.name if node.is_a?(CustomizedLibxml::EntityReference)
end

.get_attribute(element, name) ⇒ Object



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/moxml/adapter/libxml.rb', line 476

def get_attribute(element, name)
  native_elem = unpatch_node(element)
  return nil unless native_elem
  return nil unless native_elem.attributes?

  attr = native_elem.attributes.get_attribute(name.to_s)
  return nil unless attr

  # Extend the attribute with to_xml method for proper escaping
  attr.define_singleton_method(:to_xml) do
    escaped = value.to_s
      .gsub("&", "&amp;")
      .gsub("<", "&lt;")
      .gsub(">", "&gt;")
      .gsub("\"", "&quot;")
    "#{name} = #{escaped}"
  end
  attr
end

.get_attribute_value(element, name) ⇒ Object



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/moxml/adapter/libxml.rb', line 496

def get_attribute_value(element, name)
  native_elem = unpatch_node(element)
  return nil unless native_elem

  name_s = name.to_s
  if name_s.include?(":")
    prefix, local_name = name_s.split(":", 2)
    # Try to find attribute by namespace
    if native_elem.attributes?
      native_elem.each_attr do |attr|
        if [local_name, name_s].include?(attr.name)
          # Check if attribute's namespace matches the prefix
          if attr.ns && attr.ns.prefix == prefix
            return attr.value
          elsif attr.name == name_s
            # Fallback: attribute name includes the prefix
            return attr.value
          end
        end
      end
    end

    return nil
  end

  # Bare name: node[name_s] is ambiguous when a namespaced
  # attribute shares the local name (issue #94), so prefer the
  # namespace-less attribute explicitly.
  if native_elem.attributes?
    namespaced_value = nil
    native_elem.each_attr do |attr|
      next if attr.name.to_s.start_with?("xmlns")
      next unless attr.name == name_s

      if attr.ns.nil?
        return attr.value
      elsif namespaced_value.nil?
        namespaced_value = attr.value
      end
    end
    return namespaced_value unless namespaced_value.nil?
  end

  native_elem[name_s]
end

.has_declaration?(native_doc, wrapper) ⇒ Boolean

Returns:

  • (Boolean)


1045
1046
1047
1048
1049
1050
1051
1052
# File 'lib/moxml/adapter/libxml.rb', line 1045

def has_declaration?(native_doc, wrapper)
  decl = attachments.get(native_doc, :declaration)
  if decl
    !decl.removed
  else
    wrapper.has_xml_declaration
  end
end

.inner_text(node) ⇒ Object



769
770
771
772
773
774
775
776
777
778
779
# File 'lib/moxml/adapter/libxml.rb', line 769

def inner_text(node)
  native_node = unpatch_node(node)
  return "" unless native_node
  return "" unless native_node.children?

  result = []
  native_node.each_child do |child|
    result << child.content if child.text?
  end
  result.join
end

.line_number(node) ⇒ Object



403
404
405
406
# File 'lib/moxml/adapter/libxml.rb', line 403

def line_number(node)
  native = unpatch_node(node)
  native.is_a?(::LibXML::XML::Node) ? native.line_num : nil
end

.namespace(element) ⇒ Object



884
885
886
887
888
889
890
891
892
# File 'lib/moxml/adapter/libxml.rb', line 884

def namespace(element)
  native_elem = unpatch_node(element)
  return nil unless native_elem

  # Return ONLY the element's own namespace
  # Do NOT inherit parent namespaces (prefixed namespaces are NOT inherited)
  # Only default namespaces are inherited during element creation by LibXML
  native_elem.namespaces&.namespace
end

.namespace_definitions(node) ⇒ Object



902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
# File 'lib/moxml/adapter/libxml.rb', line 902

def namespace_definitions(node)
  native_node = unpatch_node(node)
  return [] unless native_node
  return [] unless native_node.is_a?(::LibXML::XML::Node)

  namespaces = native_node.namespaces
  return [] unless namespaces

  namespace_list =
    if namespaces.is_a?(::LibXML::XML::Namespaces)
      namespaces.definitions
    else
      namespaces
    end

  namespace_list.to_a
end

.namespace_prefix(namespace) ⇒ Object



894
895
896
# File 'lib/moxml/adapter/libxml.rb', line 894

def namespace_prefix(namespace)
  namespace&.prefix
end

.namespace_uri(namespace) ⇒ Object



898
899
900
# File 'lib/moxml/adapter/libxml.rb', line 898

def namespace_uri(namespace)
  namespace&.href
end

.next_sibling(node) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
# File 'lib/moxml/adapter/libxml.rb', line 363

def next_sibling(node)
  native_node = unpatch_node(node)
  current = native_node&.next
  while current
    # Skip whitespace-only text nodes
    break unless blank_text_node?(current)

    current = current.next
  end
  current ? patch_node(current) : nil
end

.node_name(node) ⇒ Object



259
260
261
262
# File 'lib/moxml/adapter/libxml.rb', line 259

def node_name(node)
  native_node = unpatch_node(node)
  native_node&.name
end

.node_type(node) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/moxml/adapter/libxml.rb', line 237

def node_type(node)
  return :unknown unless node

  # Fast path: native libxml nodes are the vast majority during
  # parse traversal (wrapping visits raw libxml children).
  # Skip the wrapper checks below for them.
  if node.is_a?(::LibXML::XML::Node)
    return NATIVE_NODE_TYPE_MAP[node.node_type] || :unknown
  end
  return :document if node.is_a?(::LibXML::XML::Document)

  wrapper_type = WRAPPER_NODE_TYPE_MAP[node.class]
  return wrapper_type if wrapper_type

  # Duck-typed fallback for libxml types that aren't ::Node
  # subclasses but still expose node_type (e.g. ::Attr).
  native = unpatch_node(node)
  return :unknown unless native.is_a?(::LibXML::XML::Node)

  NATIVE_NODE_TYPE_MAP[native.node_type] || :unknown
end

.parent(node) ⇒ Object



357
358
359
360
361
# File 'lib/moxml/adapter/libxml.rb', line 357

def parent(node)
  native_node = unpatch_node(node)
  parent_node = native_node&.parent
  parent_node ? patch_node(parent_node) : nil
end

.parse(xml, options = {}, _context = nil) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/moxml/adapter/libxml.rb', line 86

def parse(xml, options = {}, _context = nil)
  # LibXML doesn't preserve DOCTYPE during parsing, so we need to extract it manually
  xml_string = if xml.is_a?(String)
                 xml
               elsif xml.is_a?(IO) || xml.is_a?(StringIO)
                 xml.read
               else
                 xml.to_s
               end

  # Preprocess entities before parsing.
  # This converts the string to UTF-8; LibXML will use the encoding
  # parameter or XML declaration for byte interpretation.
  xml_string = preprocess_entities(xml_string)

  # Extract DOCTYPE before parsing. Locate the literal first:
  # a plain memscan is ~2x cheaper than the regex's literal
  # prefix scan on doctype-less documents (the common case),
  # and matching from the found offset keeps captures
  # identical.
  doctype_idx = xml_string.index("<!DOCTYPE")
  doctype_match = if doctype_idx
                    xml_string.match(DOCTYPE_RE, doctype_idx)
                  end

  native_doc = begin
    # Handle both string and file inputs
    parser = ::LibXML::XML::Parser.string(xml_string)
    parser.parse
  rescue ::LibXML::XML::Error => e
    if options[:strict]
      line = e.line
      raise Moxml::ParseError.new(
        e.message,
        line: line,
        column: nil,
        source: xml_string[0..100],
      )
    end
    # Return empty document for non-strict mode
    create_document
  end

  # Store DOCTYPE if found
  if doctype_match
    name = doctype_match[1]
    external_id = doctype_match[2]
    system_id = doctype_match[3] || doctype_match[4]

    doctype_wrapper = DoctypeWrapper.new(
      native_doc,
      name,
      external_id,
      system_id,
    )
    attachments.set(native_doc, :doctype, doctype_wrapper)
  end

  ctx = _context || Context.new(:libxml)
  # Single parse path: wrap libxml's already-complete C-parsed tree
  # directly (same pattern as the other adapters).
  # Doctype/declaration/PI attachments set above remain on
  # native_doc, so the serialize path still sees them.
  #
  # restore_entities is handled as a post-processing case after
  # the wrap, NOT by branching into a different builder. This way
  # any new parse-time logic only has to be added to this one
  # path; the restoration walk is just one of potentially several
  # post-processing steps and doesn't fork the construction.
  doc = Document.new(native_doc, ctx)
  Entity::Restorer.new(doc).run if ctx.config.restore_entities
  doc
end

.patch_node(node, _parent = nil) ⇒ Object



1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'lib/moxml/adapter/libxml.rb', line 1014

def patch_node(node, _parent = nil)
  # Wrap native LibXML nodes in our wrapper classes
  return node if node.nil?
  return node if node.is_a?(CustomizedLibxml::Node)

  case node_type(node)
  when :element
    CustomizedLibxml::Element.new(node)
  when :text
    CustomizedLibxml::Text.new(node)
  when :cdata
    CustomizedLibxml::Cdata.new(node)
  when :comment
    CustomizedLibxml::Comment.new(node)
  when :processing_instruction
    CustomizedLibxml::ProcessingInstruction.new(node)
  else
    node
  end
end

.patches_children?Boolean

Returns:

  • (Boolean)


1010
1011
1012
# File 'lib/moxml/adapter/libxml.rb', line 1010

def patches_children?
  true
end

.previous_sibling(node) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
# File 'lib/moxml/adapter/libxml.rb', line 375

def previous_sibling(node)
  native_node = unpatch_node(node)
  current = native_node&.prev
  while current
    # Skip whitespace-only text nodes
    break unless blank_text_node?(current)

    current = current.prev
  end
  current ? patch_node(current) : nil
end

.processing_instruction_content(node) ⇒ Object



845
846
847
848
# File 'lib/moxml/adapter/libxml.rb', line 845

def processing_instruction_content(node)
  # XML 1.0 §2.6: PI content is verbatim — no entity resolution.
  unpatch_node(node)&.content
end

.processing_instruction_target(node) ⇒ Object



840
841
842
843
# File 'lib/moxml/adapter/libxml.rb', line 840

def processing_instruction_target(node)
  native_node = unpatch_node(node)
  native_node&.name
end

.remove(node) ⇒ Object



693
694
695
696
697
698
699
700
701
702
# File 'lib/moxml/adapter/libxml.rb', line 693

def remove(node)
  # Handle Declaration wrapper - mark as removed on document
  if node.is_a?(CustomizedLibxml::Declaration)
    node.removed = true
    return
  end

  native_node = unpatch_node(node)
  native_node&.remove!
end

.remove_attribute(element, name) ⇒ Object



542
543
544
545
546
547
548
549
# File 'lib/moxml/adapter/libxml.rb', line 542

def remove_attribute(element, name)
  native_elem = unpatch_node(element)
  return unless native_elem
  return unless native_elem.attributes?

  attr = native_elem.attributes.get_attribute(name.to_s)
  attr&.remove!
end

.remove_attribute_native(attr) ⇒ Object



551
552
553
# File 'lib/moxml/adapter/libxml.rb', line 551

def remove_attribute_native(attr)
  attr&.remove!
end

.remove_declaration(native_doc) ⇒ Object



1054
1055
1056
1057
# File 'lib/moxml/adapter/libxml.rb', line 1054

def remove_declaration(native_doc)
  decl = attachments.get(native_doc, :declaration)
  decl&.removed = true
end

.replace(node, new_node) ⇒ Object



704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
# File 'lib/moxml/adapter/libxml.rb', line 704

def replace(node, new_node)
  native_node = unpatch_node(node)
  native_new = unpatch_node(new_node)
  parent = native_node&.parent
  return unless parent && native_new

  # Special handling for text nodes - LibXML's sibling manipulation
  # doesn't work reliably for text nodes. Instead, use parent.content
  # for text-to-text replacement
  if native_node.text? && native_new.text?
    parent.content = native_new.content
    return
  end

  # Save the prev/next siblings before removing
  prev_sibling = native_node.prev
  next_sibling = native_node.next

  # Import if needed for cross-document operations
  parent_doc = parent.is_a?(::LibXML::XML::Node) ? parent.doc : nil

  # Use import_and_add to properly handle document adoption
  import_and_add(parent_doc, parent, native_new)

  # Now adjust the position - move new node to where old node was
  if prev_sibling
    # Insert after the previous sibling
    prev_sibling.next = native_new
  end
  if next_sibling
    # Insert before the next sibling
    next_sibling.prev = native_new
  end

  # Finally remove the old node
  native_node.remove!
end

.replace_children(element, children) ⇒ Object



742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/moxml/adapter/libxml.rb', line 742

def replace_children(element, children)
  native_elem = unpatch_node(element)
  return unless native_elem

  # Remove all existing children first
  native_elem.each_child(&:remove!)

  # Get the element's document for importing
  doc = native_elem.is_a?(::LibXML::XML::Node) ? native_elem.doc : nil

  children.each do |c|
    native_c = unpatch_node(c)

    # Use import_and_add helper which handles all the edge cases
    import_and_add(doc, native_elem, native_c)
  end
end

.replace_native_verbatim(node, fresh) ⇒ Object

libxml-ruby's node.content= pre-escapes; building a fresh node via new_ stores content verbatim. Swap in place and re-point the wrapper.



813
814
815
816
817
818
819
# File 'lib/moxml/adapter/libxml.rb', line 813

def replace_native_verbatim(node, fresh)
  native = unpatch_node(node)
  return unless native.is_a?(::LibXML::XML::Node)

  swap_native_in_place(native, fresh)
  node.replace_native!(fresh) if node.is_a?(CustomizedLibxml::Node)
end

.root(document) ⇒ Object



398
399
400
401
# File 'lib/moxml/adapter/libxml.rb', line 398

def root(document)
  native_doc = unpatch_node(document)
  native_doc&.root
end

.sax_parse(xml, handler) ⇒ void

This method returns an undefined value.

SAX parsing implementation for LibXML

Parameters:



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/moxml/adapter/libxml.rb', line 165

def sax_parse(xml, handler)
  # Create bridge that translates LibXML SAX to Moxml SAX
  bridge = LibXMLSAXBridge.new(handler)

  # Create LibXML SAX parser
  parser = ::LibXML::XML::SaxParser.string(xml.to_s)

  # Set callbacks
  parser.callbacks = bridge

  # Parse
  parser.parse
rescue ::LibXML::XML::Error => e
  line = e.line
  column = begin
    e.column
  rescue StandardError
    nil
  end
  error = Moxml::ParseError.new(e.message, line: line, column: column)
  handler.on_error(error)
end

.set_attribute(element, name, value) ⇒ Object



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/moxml/adapter/libxml.rb', line 434

def set_attribute(element, name, value)
  native_elem = unpatch_node(element)
  return unless native_elem

  name_str = name.to_s
  value_str = value.to_s

  # Check if attribute name contains namespace prefix
  if name_str.include?(":")
    prefix, local_name = name_str.split(":", 2)

    # Find the namespace with the given prefix
    ns = find_namespace_by_prefix(native_elem, prefix)

    if ns
      # LibXML::XML::Attr.new accepts namespace as third parameter
      # First remove existing attribute if present
      existing = native_elem.attributes.get_attribute(name_str)
      existing&.remove!

      # Create new attribute with namespace
      # Attr.new(node, name, value, ns)
      ::LibXML::XML::Attr.new(native_elem, local_name, value_str, ns)

      # Return the created attribute

    else
      # Namespace not found, set as regular attribute
      native_elem[name_str] = value_str
      native_elem.attributes.get_attribute(name_str)
    end
  else
    # node[]= is ambiguous when a namespace-bound attribute
    # shares the local name (it clobbers that attribute);
    # create or replace the no-namespace attribute explicitly.
    native_elem.each_attr do |attr|
      attr.remove! if !attr.ns && attr.name == name_str
    end if native_elem.attributes?
    ::LibXML::XML::Attr.new(native_elem, name_str, value_str)
  end
end

.set_attribute_name(attribute, new_name) ⇒ Object



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/moxml/adapter/libxml.rb', line 555

def set_attribute_name(attribute, new_name)
  # LibXML attributes cannot be renamed directly
  # We must work at the element level
  return unless attribute

  # Get values FIRST before any removal
  old_name = attribute.name
  value = attribute.value
  element = attribute.parent
  return unless element

  # Remove old attribute via element
  element.attributes.get_attribute(old_name)&.remove!

  # Add new attribute with same value
  element[new_name.to_s] = value

  # Return the new attribute
  element.attributes.get_attribute(new_name.to_s)
end

.set_cdata_content(node, content) ⇒ Object



827
828
829
# File 'lib/moxml/adapter/libxml.rb', line 827

def set_cdata_content(node, content)
  replace_native_verbatim(node, ::LibXML::XML::Node.new_cdata(content.to_s))
end

.set_comment_content(node, content) ⇒ Object



836
837
838
# File 'lib/moxml/adapter/libxml.rb', line 836

def set_comment_content(node, content)
  replace_native_verbatim(node, ::LibXML::XML::Node.new_comment(content.to_s))
end

.set_declaration_attribute(node, name, value) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/moxml/adapter/libxml.rb', line 296

def set_declaration_attribute(node, name, value)
  return unless node

  # Handle Declaration wrapper
  return unless node.is_a?(CustomizedLibxml::Declaration)

  case name
  when "version"
    node.version = value
  when "encoding"
    node.encoding = value
  when "standalone"
    # Pass the value directly - Declaration handles the conversion
    node.standalone = value
  end

  # Native documents are read-only, do nothing for them
end

.set_namespace(element, ns) ⇒ Object



876
877
878
879
880
881
882
# File 'lib/moxml/adapter/libxml.rb', line 876

def set_namespace(element, ns)
  native_elem = unpatch_node(element)
  return element unless native_elem

  native_elem.namespaces.namespace = ns if ns
  element
end

.set_node_name(node, name) ⇒ Object



264
265
266
267
# File 'lib/moxml/adapter/libxml.rb', line 264

def set_node_name(node, name)
  native_node = unpatch_node(node)
  native_node.name = name.to_s if native_node
end

.set_processing_instruction_content(node, content) ⇒ Object



850
851
852
853
854
855
856
857
858
# File 'lib/moxml/adapter/libxml.rb', line 850

def set_processing_instruction_content(node, content)
  native_node = unpatch_node(node)
  return unless native_node.is_a?(::LibXML::XML::Node)

  replace_native_verbatim(
    node,
    ::LibXML::XML::Node.new_pi(native_node.name, content.to_s),
  )
end

.set_root(doc, element) ⇒ Object



75
76
77
# File 'lib/moxml/adapter/libxml.rb', line 75

def set_root(doc, element)
  doc.root = element
end

.set_text_content(node, content) ⇒ Object



781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/moxml/adapter/libxml.rb', line 781

def set_text_content(node, content)
  native_node = unpatch_node(node)
  return unless native_node.is_a?(::LibXML::XML::Node)

  # Text wrapper: swap with new_text to preserve verbatim storage.
  # Element wrapper: let libxml manage the child text node.
  if native_node.text?
    replace_native_verbatim(node, ::LibXML::XML::Node.new_text(content.to_s))
  else
    native_node.content = content.to_s
  end
end

.swap_native_in_place(old_native, fresh) ⇒ Object

Replace old_native with fresh, preserving position. Both neighbor pointers are set explicitly to match replace's semantics (see #replace above).



797
798
799
800
801
802
803
804
805
806
807
# File 'lib/moxml/adapter/libxml.rb', line 797

def swap_native_in_place(old_native, fresh)
  parent = old_native.parent
  return if parent.nil?

  prev_sibling = old_native.prev
  next_sibling = old_native.next
  old_native.remove!
  prev_sibling.next = fresh if prev_sibling
  next_sibling.prev = fresh if next_sibling
  parent << fresh unless prev_sibling || next_sibling
end

.text_content(node) ⇒ Object



760
761
762
763
764
765
766
767
# File 'lib/moxml/adapter/libxml.rb', line 760

def text_content(node)
  return "" if node.is_a?(CustomizedLibxml::EntityReference)

  native_node = unpatch_node(node)
  return nil unless native_node

  native_node.content
end

.unpatch_node(node) ⇒ Object



1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/moxml/adapter/libxml.rb', line 1035

def unpatch_node(node)
  # Unwrap to get native LibXML node
  case node
  when CustomizedLibxml::Node, CustomizedLibxml::Declaration, DoctypeWrapper
    node.native
  else
    node
  end
end

.wrappers_recyclable?Boolean

libxml-ruby mints a fresh Ruby object for the same C node on each access; the wrapper identity map would accumulate dead entries without bound at full mutation throughput.

Returns:

  • (Boolean)


82
83
84
# File 'lib/moxml/adapter/libxml.rb', line 82

def wrappers_recyclable?
  false
end

.xpath(node, expression, namespaces = nil) ⇒ Object



934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# File 'lib/moxml/adapter/libxml.rb', line 934

def xpath(node, expression, namespaces = nil)
  native_node = unpatch_node(node)
  return [] unless native_node

  # Build namespace context for LibXML
  # LibXML requires ALL prefixes in the XPath to be registered
  ns_context = build_xpath_namespaces(native_node, namespaces)

  found = if ns_context.empty?
            native_node.find(expression)
          else
            native_node.find(expression, ns_context)
          end

  # find returns an XPath::Object for node results, scalars for
  # count()/string()/boolean functions (adapter contract)
  return found if found.is_a?(Float) || found.is_a?(String) ||
    [true, false].include?(found)

  found.to_a.map { |n| patch_node(n) }
rescue ::LibXML::XML::Error => e
  raise Moxml::XPathError.new(
    e.message,
    expression: expression,
    adapter: "LibXML",
    node: node,
  )
end