Class: Moxml::Adapter::Ox

Inherits:
Base
  • Object
show all
Defined in:
lib/moxml/adapter/ox.rb

Direct Known Subclasses

HeadedOx

Constant Summary

Constants included from XmlUtils

XmlUtils::VALID_ELEMENT_NAMES

Class Method Summary collapse

Methods inherited from Base

actual_native, attribute_name, bare_get_qname_safe?, bulk_materialize?, children_accepts_entity_flag?, create_cdata, create_comment, create_declaration, create_doctype, create_element, create_entity_reference, create_namespace, create_processing_instruction, create_text, decode_entities, digest, entity_bearing?, expanded_attr_reads?, expanded_attr_value, free_document, in_scope_namespaces, iterparse, iterparse_file, line_number, materialize_fields, native_inclusive10, parse_errors, parse_html, preprocess_entities, restore_entities, same_node?, sax_supported?, serialize_generation, source_position, walk_descendants, wrap_native, wrappers_recyclable?

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

.add_child(element, child) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/moxml/adapter/ox.rb', line 459

def add_child(element, child)
  if element.is_a?(::Ox::Document) && child.is_a?(::Ox::Instruct) && child.target == "xml"
    element.attributes ||= {}
    element.attributes[:version] = child.attributes["version"] if child.attributes["version"]
    element.attributes[:encoding] = child.attributes["encoding"] if child.attributes["encoding"]
    element.attributes[:standalone] = child.attributes["standalone"] if child.attributes["standalone"]
    attachments.set(element, :decl_explicit, {
                      encoding: child.attributes.key?("encoding") ? child.attributes["encoding"] : nil,
                      standalone: child.attributes.key?("standalone") ? child.attributes["standalone"] : nil,
                    })
    return
  end

  child.parent = element if child.is_a?(::Ox::Node)
  element.nodes ||= []

  # Insert doctype before root element in document
  if element.is_a?(::Ox::Document) && child.is_a?(::Ox::DocType)
    root_idx = element.nodes.index { |n| n.is_a?(::Ox::Element) }
    if root_idx
      element.nodes.insert(root_idx, child)
    else
      element.nodes << child
    end
  else
    element.nodes << child
  end

  # Mark document if EntityReference is added (avoids tree scan in serialize)
  if child.is_a?(::Moxml::Adapter::CustomizedOx::EntityReference)
    root = element
    while root.is_a?(::Ox::Node) && root.parent
      root = root.parent
    end
    attachments.set(root, :has_entity_refs, true) if root
  end
end

.add_next_sibling(node, sibling) ⇒ Object



508
509
510
511
512
513
514
515
516
517
# File 'lib/moxml/adapter/ox.rb', line 508

def add_next_sibling(node, sibling)
  return unless (parent = parent(node))

  if sibling.is_a?(::Ox::Node)
    sibling.parent&.nodes&.delete(sibling)
    sibling.parent = parent
  end
  idx = parent.nodes.index(node)
  parent.nodes.insert(idx + 1, sibling) if idx
end

.add_previous_sibling(node, sibling) ⇒ Object



497
498
499
500
501
502
503
504
505
506
# File 'lib/moxml/adapter/ox.rb', line 497

def add_previous_sibling(node, sibling)
  return unless (parent = parent(node))

  if sibling.is_a?(::Ox::Node)
    sibling.parent&.nodes&.delete(sibling)
    sibling.parent = parent
  end
  idx = parent.nodes.index(node)
  parent.nodes.insert(idx, sibling) if idx
end

.ancestors(node) ⇒ Object



226
227
228
229
230
# File 'lib/moxml/adapter/ox.rb', line 226

def ancestors(node)
  return [] unless (parent = parent(node))

  [parent] + ancestors(parent)
end

.assign_parents(node, parent = nil) ⇒ Object



560
561
562
563
564
565
566
567
# File 'lib/moxml/adapter/ox.rb', line 560

def assign_parents(node, parent = nil)
  node.parent = parent if node.is_a?(::Ox::Element) && parent
  return unless node.is_a?(::Ox::Element) || node.is_a?(::Ox::Document)

  node.nodes&.each do |child|
    assign_parents(child, node)
  end
end

.at_xpath(node, expression, namespaces = {}) ⇒ Object



723
724
725
726
# File 'lib/moxml/adapter/ox.rb', line 723

def at_xpath(node, expression, namespaces = {})
  result = xpath(node, expression, namespaces)
  result.is_a?(Array) ? result.first : result
end

.attachmentsObject



14
15
16
# File 'lib/moxml/adapter/ox.rb', line 14

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

.attribute_element(attribute) ⇒ Object



374
375
376
# File 'lib/moxml/adapter/ox.rb', line 374

def attribute_element(attribute)
  attribute.parent
end

.attributes(element) ⇒ Object



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

def attributes(element)
  return [] unless element.is_a?(::Ox::Element) && element.attributes

  element.attributes.filter_map do |name, value|
    next if name.to_s.start_with?("xmlns")

    # Ensure value is passed correctly - Ox stores with symbol keys
    ::Moxml::Adapter::CustomizedOx::Attribute.new(
      name.to_s, value, element
    )
  end
end

.bare_set_qname_safe?Boolean



18
19
20
# File 'lib/moxml/adapter/ox.rb', line 18

def bare_set_qname_safe?
  true
end

.cdata_content(node) ⇒ Object



613
614
615
# File 'lib/moxml/adapter/ox.rb', line 613

def cdata_content(node)
  node.value.to_s
end

.children(node, **_entity_bearing) ⇒ Object



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/moxml/adapter/ox.rb', line 309

def children(node, **_entity_bearing)
  return [] unless node.is_a?(::Ox::Element) || node.is_a?(::Ox::Document)

  result = node.nodes || []
  # Ox doesn't set parent references during parsing.
  # Set them here so parent/sibling navigation works. The
  # != node guard skips the write for already-linked (or
  # stale-parented) children — steady-state access pays one
  # comparison instead of a mutation per child.
  result.each do |child|
    child.parent = node if child.is_a?(::Ox::Element) &&
      child.parent != node
  end
  result
end

.comment_content(node) ⇒ Object



621
622
623
# File 'lib/moxml/adapter/ox.rb', line 621

def comment_content(node)
  node.value.to_s
end

.context_adapter_nameObject

Adapter name used when wrapping bare native nodes; kept overridable so HeadedOx wraps into its own adapter.



748
749
750
# File 'lib/moxml/adapter/ox.rb', line 748

def context_adapter_name
  :ox
end

.create_document(native_doc = nil) ⇒ Object



96
97
98
99
# File 'lib/moxml/adapter/ox.rb', line 96

def create_document(native_doc = nil)
  attrs = native_doc&.attributes || {}
  ::Ox::Document.new(**attrs)
end

.create_native_cdata(content, _owner_doc = nil) ⇒ Object



120
121
122
# File 'lib/moxml/adapter/ox.rb', line 120

def create_native_cdata(content, _owner_doc = nil)
  ::Ox::CData.new(content)
end

.create_native_comment(content, _owner_doc = nil) ⇒ Object



124
125
126
# File 'lib/moxml/adapter/ox.rb', line 124

def create_native_comment(content, _owner_doc = nil)
  ::Ox::Comment.new(content)
end

.create_native_declaration(version, encoding, standalone) ⇒ Object



145
146
147
148
149
150
151
# File 'lib/moxml/adapter/ox.rb', line 145

def create_native_declaration(version, encoding, standalone)
  inst = ::Ox::Instruct.new("xml")
  set_attribute(inst, "version", version)
  set_attribute(inst, "encoding", encoding)
  set_attribute(inst, "standalone", standalone)
  inst
end

.create_native_doctype(name, external_id, system_id) ⇒ Object



128
129
130
131
132
133
134
135
136
137
# File 'lib/moxml/adapter/ox.rb', line 128

def create_native_doctype(name, external_id, system_id)
  value = if external_id
            "#{name} PUBLIC \"#{external_id}\" \"#{system_id}\""
          elsif system_id
            "#{name} SYSTEM \"#{system_id}\""
          else
            name.to_s
          end
  ::Ox::DocType.new(value)
end

.create_native_element(name, _owner_doc = nil) ⇒ Object



101
102
103
# File 'lib/moxml/adapter/ox.rb', line 101

def create_native_element(name, _owner_doc = nil)
  ::Ox::Element.new(name)
end

.create_native_entity_reference(name, _owner_doc = nil) ⇒ Object



112
113
114
# File 'lib/moxml/adapter/ox.rb', line 112

def create_native_entity_reference(name, _owner_doc = nil)
  ::Moxml::Adapter::CustomizedOx::EntityReference.new(name)
end

.create_native_namespace(element, prefix, uri) ⇒ Object



161
162
163
164
165
166
# File 'lib/moxml/adapter/ox.rb', line 161

def create_native_namespace(element, prefix, uri)
  ns = ::Moxml::Adapter::CustomizedOx::Namespace.new(prefix, uri,
                                                     element)
  set_attribute(element, ns.expanded_prefix, uri)
  ns
end

.create_native_processing_instruction(target, content) ⇒ Object



139
140
141
142
143
# File 'lib/moxml/adapter/ox.rb', line 139

def create_native_processing_instruction(target, content)
  inst = ::Ox::Instruct.new(target)
  set_processing_instruction_content(inst, content)
  inst
end

.create_native_text(content, _owner_doc = nil) ⇒ Object

Ox stores the Ruby string object itself as the node value — without the copy, later caller mutations would write through into the document (ownership shield; see set_text_content).



108
109
110
# File 'lib/moxml/adapter/ox.rb', line 108

def create_native_text(content, _owner_doc = nil)
  content.dup
end

.declaration_attribute(declaration, attr_name) ⇒ Object



153
154
155
# File 'lib/moxml/adapter/ox.rb', line 153

def declaration_attribute(declaration, attr_name)
  get_attribute_value(declaration, attr_name)
end

.dedupe_natives(natives) ⇒ Object

Identity-based dedup: uniq's value equality would collapse equal String text nodes.



734
735
736
737
738
739
740
741
742
743
744
# File 'lib/moxml/adapter/ox.rb', line 734

def dedupe_natives(natives)
  seen = {}
  natives.select do |native|
    id = native.object_id
    if seen[id]
      false
    else
      seen[id] = true
    end
  end
end

.doctype_external_id(native) ⇒ Object



673
674
675
676
677
678
# File 'lib/moxml/adapter/ox.rb', line 673

def doctype_external_id(native)
  value = native.value.to_s
  # Match PUBLIC "external_id"
  match = value.match(/PUBLIC\s+"([^"]*)"/)
  match ? match[1] : nil
end

.doctype_name(native) ⇒ Object

Doctype accessor methods Ox stores DOCTYPE as a string, so we parse it



666
667
668
669
670
671
# File 'lib/moxml/adapter/ox.rb', line 666

def doctype_name(native)
  # Parse: "name PUBLIC \"external_id\" \"system_id\"" or "name SYSTEM \"system_id\""
  value = native.value.to_s.strip
  # Extract the first word (the name)
  value.split(/\s+/).first
end

.doctype_system_id(native) ⇒ Object



680
681
682
683
684
685
686
687
# File 'lib/moxml/adapter/ox.rb', line 680

def doctype_system_id(native)
  value = native.value.to_s
  # Match the last quoted string (system_id)
  # For PUBLIC: "name PUBLIC \"external_id\" \"system_id\""
  # For SYSTEM: "name SYSTEM \"system_id\""
  matches = value.scan(/"([^"]*)"/)
  matches.last&.first
end

.document(node) ⇒ Object



345
346
347
348
349
# File 'lib/moxml/adapter/ox.rb', line 345

def document(node)
  current = node
  current = parent(current) while parent(current)
  current
end

.duplicate_node(node) ⇒ Object



270
271
272
# File 'lib/moxml/adapter/ox.rb', line 270

def duplicate_node(node)
  Marshal.load(Marshal.dump(node))
end

.entity_reference_name(node) ⇒ Object



116
117
118
# File 'lib/moxml/adapter/ox.rb', line 116

def entity_reference_name(node)
  node.name if node.is_a?(::Moxml::Adapter::CustomizedOx::EntityReference)
end

.get_attribute(element, name) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/moxml/adapter/ox.rb', line 426

def get_attribute(element, name)
  return unless element.is_a?(::Ox::HasAttrs) && element.attributes
  unless element.attributes.key?(name.to_s) || element.attributes.key?(name.to_s.to_sym)
    return
  end

  # Ox stores attributes with symbol keys, so try both string and symbol
  value = element.attributes[name.to_s] || element.attributes[name.to_s.to_sym]

  ::Moxml::Adapter::CustomizedOx::Attribute.new(
    name.to_s, value, element
  )
end

.get_attribute_value(element, name) ⇒ Object



440
441
442
# File 'lib/moxml/adapter/ox.rb', line 440

def get_attribute_value(element, name)
  element[name]
end

.has_declaration?(native_doc, _wrapper) ⇒ Boolean



819
820
821
# File 'lib/moxml/adapter/ox.rb', line 819

def has_declaration?(native_doc, _wrapper)
  native_doc[:version] || native_doc[:encoding] || native_doc[:standalone]
end

.inner_text(node) ⇒ Object



596
597
598
599
600
# File 'lib/moxml/adapter/ox.rb', line 596

def inner_text(node)
  return "" unless node.is_a?(::Ox::Element) || node.is_a?(::Ox::Document)

  node.nodes.grep(String).join
end

.namespace(element) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/moxml/adapter/ox.rb', line 191

def namespace(element)
  prefix =
    if element.is_a?(::Moxml::Adapter::CustomizedOx::Attribute)
      element.prefix
    elsif element.name.include?(":")
      element.name.split(":").first
    end

  # Unprefixed attributes are in no namespace — the default
  # namespace declaration does not apply to attribute names
  # (Namespaces 1.0 §5.2). Unprefixed elements DO take it.
  return nil if element.is_a?(::Moxml::Adapter::CustomizedOx::Attribute) && prefix.nil?

  # Namespaces 1.0 §4: xml is prebound; no declaration required.
  if prefix == "xml"
    return ::Moxml::Adapter::CustomizedOx::Namespace.new(
      prefix, Moxml::AttributeResolver::XML_NAMESPACE_URI, element
    )
  end

  attr_name = ["xmlns", prefix].compact.join(":")

  ([element] + ancestors(element)).each do |node|
    next unless node.is_a?(::Ox::Element) && node.attributes

    if node[attr_name]
      return ::Moxml::Adapter::CustomizedOx::Namespace.new(
        prefix, node[attr_name], element
      )
    end
  end

  nil
end

.namespace_definitions(node) ⇒ Object



649
650
651
652
653
654
655
656
657
658
659
660
661
662
# File 'lib/moxml/adapter/ox.rb', line 649

def namespace_definitions(node)
  return [] unless node.is_a?(::Ox::Element) && node.attributes

  namespaces = {}
  node.attributes.each do |name, value|
    name_s = name.to_s
    next unless name_s == "xmlns" || name_s.start_with?("xmlns:")

    namespaces[name] = ::Moxml::Adapter::CustomizedOx::Namespace.new(
      name, value, node
    )
  end
  namespaces.values
end

.namespace_prefix(namespace) ⇒ Object



637
638
639
640
641
642
643
# File 'lib/moxml/adapter/ox.rb', line 637

def namespace_prefix(namespace)
  # Ox spells the default namespace's prefix "xmlns"; the
  # wrapper contract is nil there (parity with the other
  # adapters' in-scope maps).
  prefix = namespace.prefix
  prefix == "xmlns" ? nil : prefix
end

.namespace_uri(namespace) ⇒ Object



645
646
647
# File 'lib/moxml/adapter/ox.rb', line 645

def namespace_uri(namespace)
  namespace.uri
end

.native_identity_stable?Boolean



22
23
24
# File 'lib/moxml/adapter/ox.rb', line 22

def native_identity_stable?
  true
end

.needs_custom_serialize?(node) ⇒ Boolean



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/moxml/adapter/ox.rb', line 768

def needs_custom_serialize?(node)
  # Fast path: single CData with ]]>
  return true if node.is_a?(::Ox::CData) && node.value&.include?("]]>")

  # Only documents/elements can contain entity refs or CDATA issues
  return false unless node.is_a?(::Ox::Document) || node.is_a?(::Ox::Element)

  # Element serializes consult the owning document's cached
  # flags — a rescan per call made element to_xml ~30x slower
  # than document to_xml on plain documents.
  scan_root = node
  if node.is_a?(::Ox::Element) && (doc = document(node))
    return true if attachments.get(doc, :has_entity_refs)
    return true if attachments.get(doc, :has_cdata_end_markers)
    return false if attachments.key?(doc, :has_entity_refs) &&
      attachments.key?(doc, :has_cdata_end_markers)

    scan_root = doc
  end

  # One merged tree scan instead of two; flags cache on the
  # document either way.
  has_er, has_cdata = tree_scan_custom_needs(scan_root)
  if scan_root.is_a?(::Ox::Document)
    attachments.set(scan_root, :has_entity_refs, has_er)
    attachments.set(scan_root, :has_cdata_end_markers, has_cdata)
  end

  has_er || has_cdata
end

.next_sibling(node) ⇒ Object



329
330
331
332
333
334
335
# File 'lib/moxml/adapter/ox.rb', line 329

def next_sibling(node)
  return unless (parent = node.parent)

  siblings = parent.nodes
  idx = siblings.index(unpatch_node(node))
  idx ? patch_node(siblings[idx + 1], parent) : nil
end

.node_name(node) ⇒ Object



252
253
254
255
256
257
258
259
260
261
# File 'lib/moxml/adapter/ox.rb', line 252

def node_name(node)
  name = begin
    node.value
  rescue StandardError
    node.name
  end

  # Strip namespace prefix if present
  name.to_s.split(":", 2).last
end

.node_type(node) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/moxml/adapter/ox.rb', line 236

def node_type(node)
  case node
  when ::Ox::Document then :document
  when ::Moxml::Adapter::CustomizedOx::Text, String then :text
  when ::Ox::CData then :cdata
  when ::Ox::Comment then :comment
  when ::Ox::Instruct then :processing_instruction
  when ::Ox::Element then :element
  when ::Ox::DocType then :doctype
  when ::Moxml::Adapter::CustomizedOx::EntityReference then :entity_reference
  when ::Moxml::Adapter::CustomizedOx::Namespace then :namespace
  when ::Moxml::Adapter::CustomizedOx::Attribute then :attribute
  else :unknown
  end
end

.parent(node) ⇒ Object



325
326
327
# File 'lib/moxml/adapter/ox.rb', line 325

def parent(node)
  node.parent if node.is_a?(::Ox::Node)
end

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/moxml/adapter/ox.rb', line 39

def parse(xml, options = {}, _context = nil)
  processed_xml = preprocess_entities(xml)
  native_doc = begin
    # ::Ox.parse has arity 1 and hardcodes skip: :skip_white;
    # ::Ox.load takes the policy (issue #189). Both knobs flow
    # from Config through Context#default_options; the fetch
    # defaults keep direct adapter calls context-free.
    result = ::Ox.load(
      processed_xml,
      skip: options.fetch(:ox_skip, Moxml::Config::OX_DEFAULT_SKIP),
      mode: options.fetch(:ox_mode, Moxml::Config::OX_DEFAULT_MODE),
    )

    # result can be either Document or Element
    if result.is_a?(::Ox::Document)
      assign_parents(result)
      validate_single_root(result) if options[:strict]
      result
    else
      doc = ::Ox::Document.new
      doc << result
      assign_parents(doc)
      doc
    end
  rescue ::Ox::ParseError => e
    raise Moxml::ParseError.new(
      e.message,
      source: xml.is_a?(String) ? xml[0..100] : nil,
    )
  end

  ctx = _context || Context.new(context_adapter_name)
  Wrappers::Document.new(native_doc, ctx)
end

.parse_fragment(xml, _context = nil) ⇒ Object



351
352
353
354
355
# File 'lib/moxml/adapter/ox.rb', line 351

def parse_fragment(xml, _context = nil)
  doc = parse("<m>#{xml}</m>").native
  synthetic = doc.nodes.find { |node| node.is_a?(::Ox::Element) }
  children(synthetic)
end

.patch_node(node, parent = nil) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/moxml/adapter/ox.rb', line 278

def patch_node(node, parent = nil)
  new_node =
    case node
    # it can be either attribute or namespace
    when Array then ::Moxml::Adapter::CustomizedOx::Attribute.new(
      node.first, node.last
    )
    when Hash then ::Moxml::Adapter::CustomizedOx::Attribute.new(
      node.keys.first, node.values.first
    )
    when String then ::Moxml::Adapter::CustomizedOx::Text.new(node)
    else node
    end

  new_node.parent = parent if new_node.is_a?(::Ox::Node)

  new_node
end

.patches_children?Boolean



274
275
276
# File 'lib/moxml/adapter/ox.rb', line 274

def patches_children?
  true
end

.previous_sibling(node) ⇒ Object



337
338
339
340
341
342
343
# File 'lib/moxml/adapter/ox.rb', line 337

def previous_sibling(node)
  return unless (parent = parent(node))

  siblings = parent.nodes
  idx = siblings.index(unpatch_node(node))
  idx&.positive? ? patch_node(siblings[idx - 1], parent) : nil
end

.processing_instruction_content(node) ⇒ Object



629
630
631
# File 'lib/moxml/adapter/ox.rb', line 629

def processing_instruction_content(node)
  node.content.to_s
end

.processing_instruction_target(node) ⇒ Object



232
233
234
# File 'lib/moxml/adapter/ox.rb', line 232

def processing_instruction_target(node)
  node.target
end

.remove(node) ⇒ Object



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/moxml/adapter/ox.rb', line 519

def remove(node)
  return node.clear if node.is_a?(String)

  return unless parent(node)

  # Special handling for declarations on Ox documents
  if parent(node).is_a?(::Ox::Document) && node.is_a?(::Ox::Instruct) && node.target == "xml"
    # Clear declaration attributes from document
    doc = parent(node)
    doc.attributes&.delete(:version)
    doc.attributes&.delete(:encoding)
    doc.attributes&.delete(:standalone)
  end

  parent(node).nodes.delete(unpatch_node(node))
end

.remove_attribute(element, name) ⇒ Object



444
445
446
447
448
449
# File 'lib/moxml/adapter/ox.rb', line 444

def remove_attribute(element, name)
  return unless element.is_a?(::Ox::HasAttrs) && element.attributes

  element.attributes.delete(name.to_s)
  element.attributes.delete(name.to_s.to_sym)
end

.remove_attribute_native(attribute) ⇒ Object



451
452
453
454
455
456
457
# File 'lib/moxml/adapter/ox.rb', line 451

def remove_attribute_native(attribute)
  expanded = attribute.expanded_name
  element = attribute.parent
  element.attributes.delete(expanded)
  element.attributes.delete(expanded.to_sym)
  attribute
end

.remove_declaration(native_doc) ⇒ Object



823
824
825
826
827
828
# File 'lib/moxml/adapter/ox.rb', line 823

def remove_declaration(native_doc)
  native_doc.attributes&.delete(:version)
  native_doc.attributes&.delete(:encoding)
  native_doc.attributes&.delete(:standalone)
  attachments.delete(native_doc, :decl_explicit)
end

.replace(node, new_node) ⇒ Object



536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/moxml/adapter/ox.rb', line 536

def replace(node, new_node)
  if node.is_a?(String) && new_node.is_a?(String)
    return node.replace(new_node)
  end
  # There are other cases:
  # when node is a String and new_node isn't
  # when node isn't a String, and new_node is a String

  return unless (parent = parent(node))

  new_node.parent = parent if new_node.is_a?(::Ox::Node)
  idx = parent.nodes.index(node)
  parent.nodes[idx] = new_node if idx
end

.replace_children(node, new_children) ⇒ Object



551
552
553
554
555
556
557
558
# File 'lib/moxml/adapter/ox.rb', line 551

def replace_children(node, new_children)
  node.remove_children_by_path("*")
  new_children.each do |child|
    child.parent = node if child.is_a?(::Ox::Node)
    node << child
  end
  node
end

.root(document) ⇒ Object



357
358
359
# File 'lib/moxml/adapter/ox.rb', line 357

def root(document)
  document.nodes&.find { |node| node.is_a?(::Ox::Element) }
end

.sax_parse(xml, handler) ⇒ void

This method returns an undefined value.

SAX parsing implementation for Ox



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/moxml/adapter/ox.rb', line 79

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

  # Parse using Ox's SAX parser
  xml_string = xml.is_a?(IO) || xml.is_a?(StringIO) ? xml.read : xml.to_s

  begin
    ::Ox.sax_parse(bridge, StringIO.new(xml_string))
    # Ox doesn't automatically call end_document, so we do it manually
    bridge.end_document
  rescue ::Ox::ParseError => e
    error = Moxml::ParseError.new(e.message)
    handler.on_error(error)
  end
end

.serialize(node, options = {}) ⇒ Object



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/moxml/adapter/ox.rb', line 752

def serialize(node, options = {})
  # CustomizedOx::Text subclasses ::Ox::Node so it can carry a @parent
  # back-reference, but that makes it unknown to Ox.dump's XML emitter,
  # which then falls back to generic object marshalling. Short-circuit
  # here with proper XML escaping.
  return XmlEmitter.escape_text(node.value) if node.is_a?(CustomizedOx::Text)

  needs_custom = needs_custom_serialize?(node)

  unless needs_custom
    return serialize_standard(node, options)
  end

  serialize_custom(node, options)
end

.set_attribute(element, name, value) ⇒ Object



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/moxml/adapter/ox.rb', line 378

def set_attribute(element, name, value)
  element.attributes ||= {}
  if value.nil?
    # Ox converts all values to strings
    remove_attribute(element, name)
  else
    key = name.to_s
    attrs = element.attributes
    # Ox parses attributes under Symbol keys; a naive
    # string-keyed write would ADD a second entry instead
    # of replacing (the parity suite caught reads returning
    # the stale symbol-keyed value after a write).
    attrs.delete(key.to_sym)
    attrs[key] = value
  end

  ::Moxml::Adapter::CustomizedOx::Attribute.new(
    name.to_s, value&.to_s, element
  )
end

.set_attribute_name(attribute, name) ⇒ Object



399
400
401
402
403
404
405
406
407
# File 'lib/moxml/adapter/ox.rb', line 399

def set_attribute_name(attribute, name)
  old_name = attribute.name
  attribute.name = name.to_s
  # Ox doesn't change the keys of the attributes hash
  element = attribute.parent
  element.attributes.delete(old_name)
  element.attributes[name] = attribute.value
  attribute
end

.set_attribute_value(attribute, new_value) ⇒ Object



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

def set_attribute_value(attribute, new_value)
  if new_value.nil?
    # Ox converts all values to strings
    remove_attribute(attribute.parent, attribute.name)
  else
    element = attribute.parent
    # Rekey by the expanded name (Ox hash keys carry the
    # prefix) and collapse any symbol/string spelling of the
    # same key, or a stale symbol key shadows the new value.
    expanded = attribute.expanded_name
    element.attributes.delete(expanded.to_sym)
    element.attributes[expanded] = new_value
    attribute.value = new_value
  end
  attribute
end

.set_cdata_content(node, content) ⇒ Object



617
618
619
# File 'lib/moxml/adapter/ox.rb', line 617

def set_cdata_content(node, content)
  node.value = content.to_s
end

.set_comment_content(node, content) ⇒ Object



625
626
627
# File 'lib/moxml/adapter/ox.rb', line 625

def set_comment_content(node, content)
  node.value = content.to_s
end

.set_declaration_attribute(declaration, attr_name, value) ⇒ Object



157
158
159
# File 'lib/moxml/adapter/ox.rb', line 157

def set_declaration_attribute(declaration, attr_name, value)
  set_attribute(declaration, attr_name, value)
end

.set_namespace(element, ns) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/moxml/adapter/ox.rb', line 168

def set_namespace(element, ns)
  return element unless element.is_a?(::Ox::Element) || element.is_a?(::Ox::Node)

  if ns.nil?
    set_attribute(element, "xmlns", "")
    element.name = element.name.to_s.sub(/\A(?:\w+):/, "")
    return element
  end

  prefix = ns.prefix
  # Local part only — a qname create_element leaves
  # "p:c" and re-joining would double the prefix (#208).
  local = element.name.to_s.split(":", 2)[-1]
  element.name = prefix.nil? || prefix.empty? ? local : "#{prefix}:#{local}"
  # Declare only when the element is already in a tree and the
  # prefix is not already bound — detached create+namespace=
  # + attach under a declaring parent must not re-emit xmlns:p.
  if element.is_a?(::Ox::Element) && element.parent
    set_attribute(element, ns.expanded_prefix, ns.uri)
  end
  element
end

.set_node_name(node, name) ⇒ Object



263
264
265
266
267
268
# File 'lib/moxml/adapter/ox.rb', line 263

def set_node_name(node, name)
  case node
  when ::Ox::Element then node.name = name
  when ::Ox::Instruct then node.value = name
  end
end

.set_processing_instruction_content(node, content) ⇒ Object



633
634
635
# File 'lib/moxml/adapter/ox.rb', line 633

def set_processing_instruction_content(node, content)
  node.content = content.to_s
end

.set_root(doc, element) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/moxml/adapter/ox.rb', line 26

def set_root(doc, element)
  existing_root = root(doc)
  element.parent = doc if element.is_a?(::Ox::Node)
  if existing_root
    # Replace the existing root element, preserving other children
    idx = doc.nodes.index(existing_root)
    doc.nodes[idx] = element
  else
    # No root yet, just append the element
    doc << element
  end
end

.set_text_content(node, content) ⇒ Object



602
603
604
605
606
607
608
609
610
611
# File 'lib/moxml/adapter/ox.rb', line 602

def set_text_content(node, content)
  # Copy on the same ownership contract as create_native_text
  content = content.to_s.dup
  case node
  when String then node.replace(content)
  when ::Ox::Element then node.replace_text(content)
  else
    node.value = content.to_s
  end
end

.text_content(node) ⇒ Object



579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'lib/moxml/adapter/ox.rb', line 579

def text_content(node)
  return "" if node.nil?

  case node
  when String then node.to_s
  when ::Moxml::Adapter::CustomizedOx::Text then node.value
  when ::Ox::CData then node.value.to_s
  when ::Moxml::Adapter::CustomizedOx::EntityReference then ""
  else
    return "" unless node.is_a?(::Ox::Element) || node.is_a?(::Ox::Document)

    node.nodes.map do |n|
      text_content(n)
    end.join
  end
end

.tree_scan_custom_needs(node) ⇒ Object

Single walk collecting both custom-serialize triggers.



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
# File 'lib/moxml/adapter/ox.rb', line 800

def tree_scan_custom_needs(node)
  has_er = false
  has_cdata = false
  stack = [node]
  until stack.empty?
    current = stack.pop
    case current
    when ::Moxml::Adapter::CustomizedOx::EntityReference
      has_er = true
    when ::Ox::CData
      has_cdata = true if current.value&.include?("]]>")
    when ::Ox::Element, ::Ox::Document
      current.nodes&.each { |child| stack << child }
    end
    return [true, has_cdata] if has_er
  end
  [has_er, has_cdata]
end

.unpatch_node(node) ⇒ Object



297
298
299
300
301
302
303
304
305
306
307
# File 'lib/moxml/adapter/ox.rb', line 297

def unpatch_node(node)
  case node
  # it can be either attribute or namespace
  when ::Moxml::Adapter::CustomizedOx::Attribute then [node.name,
                                                       node.value]
  # when ::Moxml::Adapter::CustomizedOx::Attribute then { node.name => node.value }
  when ::Moxml::Adapter::CustomizedOx::Text then node.value
  when ::Moxml::Adapter::CustomizedOx::EntityReference then node
  else node
  end
end

.validate_single_root(document) ⇒ Object

Raises:



569
570
571
572
573
574
575
576
577
# File 'lib/moxml/adapter/ox.rb', line 569

def validate_single_root(document)
  elements = document.nodes&.grep(::Ox::Element) || []
  return unless elements.size > 1

  raise Moxml::ParseError.new(
    "Multiple root elements found",
    source: nil,
  )
end

.xpath(node, expression, namespaces = {}) ⇒ Object

XPath runs through Moxml's pure-Ruby XPath 1.0 engine (shared with HeadedOx and Leptris). Ox's locate() only covers a small XPath subset; the engine provides all axes, predicates, functions and variables.



693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/moxml/adapter/ox.rb', line 693

def xpath(node, expression, namespaces = {})
  wrapped = if node.is_a?(Moxml::Node)
              node
            else
              Moxml::Node.wrap(node, Context.new(context_adapter_name))
            end

  ast = XPath::Parser.parse(expression)
  proc = XPath::Compiler.compile_with_cache(ast, namespaces: namespaces)
  result = proc.call(wrapped)

  case result
  when Array
    dedupe_natives(result.map do |n|
      n.is_a?(Moxml::Node) ? n.native : n
    end)
  when NodeSet
    dedupe_natives(result.to_a.map(&:native))
  else
    result
  end
rescue StandardError => e
  raise Moxml::XPathError.new(
    "XPath execution failed: #{e.message}",
    expression: expression,
    adapter: "Ox",
    node: node,
  )
end

.xpath_supported?Boolean



728
729
730
# File 'lib/moxml/adapter/ox.rb', line 728

def xpath_supported?
  true
end