Class: Lutaml::Xml::Adapter::OgaAdapter

Inherits:
BaseAdapter show all
Extended by:
AdapterHelpers, DocTypeExtractor
Defined in:
lib/lutaml/xml/adapter/oga_adapter.rb

Constant Summary collapse

TEXT_CLASSES =
[Moxml::Text, Moxml::Cdata].freeze

Instance Attribute Summary

Attributes inherited from Document

#doctype, #encoding, #parsed_doc, #register, #root, #xml_declaration

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DocTypeExtractor

extract_doctype_from_xml

Methods included from AdapterHelpers

build_element_from_child, name_of, namespace_uri_hoisted?, namespaced_attr_name, namespaced_name_of, node_type_of, prefix_for_namespace_uri, prefixed_name_of, text_node?

Methods inherited from BaseAdapter

#add_value, #attribute_definition_for, #attribute_value_for, #build_ordered_element_with_plan, #build_unordered_children_with_plan, #child_plan_for, #determine_encoding, extract_document_processing_instructions, fpi?, fpi_to_urn, name_of, namespaced_attr_name, namespaced_name, namespaced_name_of, order_of, #ordered?, prefixed_name_of, #process_content_mapping, #render_element?

Methods included from PolymorphicValueHandler

#polymorphic_value?

Methods included from DeclarationHandler

extract_attribute, extract_xml_declaration, #generate_declaration, #generate_doctype_declaration, #should_include_declaration?

Methods inherited from Document

#add_value, #attribute_definition_for, #attribute_value_for, #attributes, #cdata, #children, #declaration, #doctype_declaration, #element_children, #element_children_index, encoding, #initialize, name_of, namespaced_name_of, order_of, #ordered?, #parse_element, #process_content_mapping, #render_element?, #text, #to_h, type

Constructor Details

This class inherits a constructor from Lutaml::Xml::Document

Class Method Details

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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 13

def self.parse(xml, options = {})
  enc = encoding(xml, options)
  # Oga requires UTF-8 encoded input; convert from other encodings
  xml = xml.encode("UTF-8") unless xml.encoding == Encoding::UTF_8
  parsed = Moxml::Adapter::Oga.parse(xml, encoding: enc)
  root_element = parsed.root

  # Validate that we have a root element
  if root_element.nil?
    raise Lutaml::Model::InvalidFormatError.new(
      :xml,
      "Document has no root element. " \
      "The XML may be empty, contain only whitespace, " \
      "or consist only of an XML declaration.",
    )
  end

  # Extract DOCTYPE information
  # Moxml/Oga doesn't directly expose DOCTYPE, extract from raw XML
  doctype_info = extract_doctype_from_xml(xml)

  @root = Oga::Element.new(root_element)
  @root.processing_instructions = extract_document_processing_instructions(parsed)
  new(@root, enc, doctype: doctype_info)
end

.text_of(element) ⇒ Object

NOTE: name_of, prefixed_name_of, namespaced_attr_name, namespaced_name_of are provided by AdapterHelpers module via extend



829
830
831
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 829

def self.text_of(element)
  element.text
end

Instance Method Details

#add_simple_value(xml, rule, value, attribute, plan: nil, mapping: nil) ⇒ Object

Add simple (non-model) values to XML



690
691
692
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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
798
799
800
801
802
803
804
805
806
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 690

def add_simple_value(xml, rule, value, attribute, plan: nil,
    mapping: nil)
  # Handle array values by creating multiple elements
  if value.is_a?(Array)
    value.each do |val|
      add_simple_value(xml, rule, val, attribute, plan: plan,
                                                  mapping: mapping)
    end
    return
  end

  # Determine prefix for this element based on namespace rules
  # Initialize namespace resolver
  resolver = NamespaceResolver.new(register)

  # Extract parent_uses_default_ns from options or calculate it
  parent_uses_default_ns = options[:parent_uses_default_ns]
  if parent_uses_default_ns.nil?
    parent_uses_default_ns = if mapping&.namespace_class && plan
                               key = mapping.namespace_class.to_key
                               ns_decl = plan.namespace(key)
                               ns_decl&.declared_here? && ns_decl.default_format?
                             else
                               false
                             end
  end

  # Resolve namespace using the resolver
  ns_result = resolver.resolve_for_element(rule, attribute, mapping,
                                           plan, options)
  ns_result[:prefix]
  type_ns_info = ns_result[:ns_info]

  # BUG FIX #49: Check if child element is in same namespace as parent
  # If yes, inherit parent's format (default vs prefix)

  # Get parent's namespace URI
  parent_ns_class = options[:parent_namespace_class]
  parent_ns_decl = options[:parent_ns_decl]
  parent_ns_uri = parent_ns_class&.uri

  # Get child's resolved namespace URI
  child_ns_uri = ns_result[:uri]

  # Initialize resolved_prefix from namespace resolution
  resolved_prefix = ns_result[:prefix]

  # CRITICAL FIX FOR NATIVE TYPE NAMESPACE INHERITANCE:
  # Elements without explicit namespace declaration should NOT inherit
  # parent's prefix format. They should be in blank namespace.
  #
  # Check if this is a native type without explicit namespace:
  # 1. No namespace directive on the mapping rule
  # 2. Attribute type doesn't have namespace_class (native type like :string)
  element_has_no_explicit_ns = !rule.namespace_set?
  type_class = attribute&.type(register)
  type_has_no_ns = !(type_class.is_a?(Class) && type_class <= Lutaml::Model::Type::Value) ||
    !type_class&.namespace_class

  # If native type with no explicit namespace, DON'T inherit parent's prefix
  if element_has_no_explicit_ns && type_has_no_ns
    # Native type - force blank namespace (no prefix)
    resolved_prefix = nil
    # Check if parent uses default format - if so, need xmlns="" to opt out
    parent_ns_decl&.default_format?
  # Only inherit format if child is in SAME namespace as parent (matching URIs)
  elsif parent_ns_class && parent_ns_decl &&
      child_ns_uri && parent_ns_uri &&
      child_ns_uri == parent_ns_uri
    # Same namespace URI - inherit parent's format
    resolved_prefix = if parent_ns_decl.prefix_format?
                        parent_ns_decl.prefix
                      else
                        # Parent uses default format, child should too (no prefix)
                        nil
                      end
  end

  # Prepare attributes with xmlns if needed
  attributes = {}

  # W3C COMPLIANCE: Use resolver to determine xmlns="" requirement
  if resolver.xmlns_blank_required?(ns_result, parent_uses_default_ns)
    attributes["xmlns"] = ""
  end

  # Check if this namespace needs local declaration (out of scope)
  if resolved_prefix && plan&.namespaces
    ns_entry = plan.namespaces.values.find do |ns_decl|
      ns_decl.ns_object.prefix_default == resolved_prefix ||
        (type_ns_info && type_ns_info[:uri] && ns_decl.ns_object.uri == type_ns_info[:uri])
    end

    if ns_entry&.local_on_use?
      xmlns_attr = resolved_prefix ? "xmlns:#{resolved_prefix}" : "xmlns"
      attributes[xmlns_attr] = ns_entry.ns_object.uri
    end
  end

  if value.nil?
    xml.create_and_add_element(rule.name,
                               attributes: attributes.merge({ "xsi:nil" => true }),
                               prefix: resolved_prefix)
  elsif ::Lutaml::Model::Utils.empty?(value)
    xml.create_and_add_element(rule.name,
                               attributes: attributes.empty? ? nil : attributes,
                               prefix: resolved_prefix)
  elsif rule.raw_mapping?
    xml.add_xml_fragment(xml, value)
  else
    xml.create_and_add_element(rule.name,
                               attributes: attributes.empty? ? nil : attributes,
                               prefix: resolved_prefix) do
      add_value(xml, value, attribute, cdata: rule.cdata)
    end
  end
end

#attributes_hash(element) ⇒ Object



808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 808

def attributes_hash(element)
  result = Lutaml::Model::MappingHash.new

  element.attributes_each_value do |attr|
    if attr.name == "schemaLocation"
      result["__schema_location"] = {
        namespace: attr.namespace,
        prefix: attr.namespace.prefix,
        schema_location: attr.value,
      }
    else
      result[self.class.namespaced_attr_name(attr)] = attr.value
    end
  end

  result
end

#build_element_with_plan(xml, element, plan, options = {}) ⇒ Object

Build element using prepared namespace declaration plan

Parameters:

  • xml (Builder)

    the XML builder

  • element (Object)

    the model instance

  • plan (Hash)

    the declaration plan from DeclarationPlanner

  • options (Hash) (defaults to: {})

    serialization options



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
295
296
297
298
299
300
301
302
303
304
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 135

def build_element_with_plan(xml, element, plan, options = {})
  mapper_class = options[:mapper_class] || element.class
  xml_mapping = mapper_class.mappings_for(:xml)
  return xml unless xml_mapping

  # TYPE-ONLY MODELS: No element wrapper, serialize children directly
  # BUT if we have a tag_name in options, that means parent wants a wrapper
  plan ||= {
    namespaces: {},
    children_plans: {},
    type_namespaces: {},
  }

  if xml_mapping.no_element?
    # If parent provided a tag_name, create that wrapper first
    if options[:tag_name]
      xml.create_and_add_element(options[:tag_name]) do |inner_xml|
        # Serialize type-only model's children inside parent's wrapper
        xml_mapping.elements.each do |element_rule|
          next if options[:except]&.include?(element_rule.to)

          attribute_def = mapper_class.attributes[element_rule.to]
          next unless attribute_def

          value = element.send(element_rule.to)
          next unless element_rule.render?(value, element)

          # For type-only models, children plans may not be available
          # Serialize children directly
          if value && attribute_def.type(register)&.<=(Lutaml::Model::Serialize)
            # Nested model - recursively build it
            child_plan = plan.child_plan(element_rule.to) || DeclarationPlan.empty
            build_element_with_plan(
              inner_xml,
              value,
              child_plan,
              { mapper_class: attribute_def.type(register),
                tag_name: element_rule.name },
            )
          else
            # Simple value - create element directly
            inner_xml.create_and_add_element(element_rule.name) do
              add_value(inner_xml, value, attribute_def,
                        cdata: element_rule.cdata)
            end
          end
        end
      end
    else
      # No wrapper at all - serialize children directly (for root-level type-only)
      xml_mapping.elements.each do |element_rule|
        next if options[:except]&.include?(element_rule.to)

        attribute_def = mapper_class.attributes[element_rule.to]
        next unless attribute_def

        value = element.send(element_rule.to)
        next unless element_rule.render?(value, element)

        child_plan = plan.child_plan(element_rule.to)

        if value && attribute_def.type(register)&.<=(Lutaml::Model::Serialize)
          handle_nested_elements_with_plan(
            xml,
            value,
            element_rule,
            attribute_def,
            child_plan,
            options,
          )
        else
          add_simple_value(xml, element_rule, value, attribute_def,
                           plan: plan, mapping: xml_mapping)
        end
      end
    end
    return xml
  end

  # Use xmlns declarations from plan
  attributes = {}

  # Apply namespace declarations from plan using extracted module
  attributes.merge!(NamespaceDeclarationBuilder.build_xmlns_attributes(plan))

  # Add regular attributes (non-xmlns)

  xml_mapping.attributes.each do |attribute_rule|
    next if attribute_rule.custom_methods[:to] ||
      options[:except]&.include?(attribute_rule.to)

    mapping_rule_name = if attribute_rule.multiple_mappings?
                          attribute_rule.name.first
                        else
                          attribute_rule.name
                        end

    attr = attribute_definition_for(element, attribute_rule,
                                    mapper_class: mapper_class)
    value = attribute_rule.to_value_for(element)

    # Handle as_list and delimiter BEFORE serialization for array values
    # These features convert arrays to delimited strings before serialization
    if value.is_a?(Array)
      if attribute_rule.as_list && attribute_rule.as_list[:export]
        value = attribute_rule.as_list[:export].call(value)
      elsif attribute_rule.delimiter
        value = value.join(attribute_rule.delimiter)
      end
    end

    value = attr.serialize(value, :xml, register) if attr
    value = ExportTransformer.call(value, attribute_rule, attr,
                                   format: :xml)

    if render_element?(attribute_rule, element, value)
      # Resolve attribute namespace using extracted module
      ns_info = AttributeNamespaceResolver.resolve(
        rule: attribute_rule,
        attribute: attr,
        plan: plan,
        mapper_class: mapper_class,
        register: register,
      )

      # Build qualified attribute name based on W3C semantics
      attr_name = AttributeNamespaceResolver.build_qualified_name(
        ns_info,
        mapping_rule_name,
        attribute_rule,
      )
      attributes[attr_name] = value ? value.to_s : value

      # Add local xmlns declaration if needed
      if ns_info[:needs_local_declaration]
        attributes[ns_info[:local_xmlns_attr]] =
          ns_info[:local_xmlns_uri]
      end
    end
  end

  # Add schema_location attribute from ElementNode if present
  # This is for the plan-based path where schema_location_attr is computed during planning
  attributes.merge!(plan.root_node.schema_location_attr) if plan&.root_node&.schema_location_attr

  # Determine prefix from plan using extracted module
  prefix_info = ElementPrefixResolver.resolve(mapping: xml_mapping,
                                              plan: plan)
  prefix = prefix_info[:prefix]

  tag_name = options[:tag_name] || xml_mapping.root_element
  return if options[:except]&.include?(tag_name)

  xml.create_and_add_element(tag_name, prefix: prefix,
                                       attributes: attributes.compact) do
    if ordered?(element, options.merge(mapper_class: mapper_class))
      build_ordered_element_with_plan(xml, element, plan,
                                      options.merge(
                                        mapper_class: mapper_class,
                                        parent_ns_decl: prefix_info[:ns_decl],
                                      ))
    else
      build_unordered_children_with_plan(xml, element, plan,
                                         options.merge(
                                           mapper_class: mapper_class,
                                           parent_ns_decl: prefix_info[:ns_decl],
                                         ))
    end
  end
end

#build_xml_element(xml, element, parent_uses_default_ns: false, parent_element_form_default: nil, parent_namespace_class: nil) ⇒ Object

Build XML from XmlDataModel::XmlElement structure

Parameters:

  • xml (Builder)

    XML builder

  • element (XmlDataModel::XmlElement)

    element to build

  • parent_uses_default_ns (Boolean) (defaults to: false)

    parent uses default namespace format

  • parent_element_form_default (Symbol) (defaults to: nil)

    parent’s element_form_default

  • parent_namespace_class (Class) (defaults to: nil)

    parent’s namespace class



313
314
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 313

def build_xml_element(xml, element, parent_uses_default_ns: false,
    parent_element_form_default: nil, parent_namespace_class: nil)
  # Prepare attributes hash
  attributes = {}

  # Determine if attributes should be qualified based on element's namespace
  element_ns_class = element.namespace_class
  attribute_form_default = element_ns_class&.attribute_form_default || :unqualified
  element_prefix = element_ns_class&.prefix_default

  # Get element_form_default for children
  this_element_form_default = element_ns_class&.element_form_default || :unqualified

  # Add regular attributes
  element.attributes.each do |attr|
    # Determine attribute name with namespace consideration
    attr_name = if attr.namespace_class
                  # Check if attribute is in SAME namespace as element
                  if attr.namespace_class == element_ns_class && attribute_form_default == :unqualified
                    # Same namespace + unqualified → NO prefix (W3C rule)
                    attr.name
                  else
                    # Different namespace OR qualified → use prefix
                    attr_prefix = attr.namespace_class.prefix_default
                    attr_prefix ? "#{attr_prefix}:#{attr.name}" : attr.name
                  end
                elsif attribute_form_default == :qualified && element_prefix
                  # Attribute inherits element's namespace when qualified
                  "#{element_prefix}:#{attr.name}"
                else
                  # Unqualified attribute
                  attr.name
                end
    attributes[attr_name] = attr.value
  end

  # Determine element name with namespace prefix
  tag_name = element.name

  # Priority 2.5: Child namespace different from parent's default namespace
  # MUST use prefix format to distinguish from parent
  child_needs_prefix = if element_ns_class && parent_namespace_class &&
      element_ns_class != parent_namespace_class && parent_uses_default_ns
                         element_prefix # Use child's prefix
                       end

  # CRITICAL FIX: element_form_default: :qualified means child elements inherit parent's namespace PREFIX
  # even when child has NO explicit namespace_class
  prefix = if child_needs_prefix
             # Priority 2.5 takes precedence
             child_needs_prefix
           elsif element_ns_class && element_prefix
             # Element has explicit prefix_default - use prefix format
             element_prefix
           elsif !element_ns_class && parent_element_form_default == :qualified && parent_namespace_class&.prefix_default
             # Child has NO namespace, but parent has :qualified form_default
             # Child should INHERIT parent's namespace PREFIX
             parent_namespace_class.prefix_default
           else
             # No prefix (default format or no parent namespace)
             nil
           end

  # Track if THIS element uses default namespace format for children
  this_element_uses_default_ns = false

  # Add namespace declaration if element has namespace
  if element.namespace_class
    ns_uri = element.namespace_class.uri

    if prefix
      attributes["xmlns:#{prefix}"] = ns_uri
      # W3C Compliance: xmlns="" only needed for blank namespace children
      # Prefixed children are already in different namespace from parent's default
    else
      attributes["xmlns"] = ns_uri
      this_element_uses_default_ns = true
    end
  elsif parent_uses_default_ns
    # W3C Compliance: Element has no namespace (blank namespace)
    # Check if should inherit parent's namespace based on element_form_default
    # Parent uses default namespace format
    if parent_element_form_default == :qualified
      # Child should INHERIT parent's namespace - no xmlns="" needed
      # The child is in parent namespace (qualified)
    else
      # Parent's element_form_default is :unqualified - child in blank namespace
      # Add xmlns="" to explicitly opt out of parent's default namespace
      attributes["xmlns"] = ""
    end
  end

  # Check if element was created from nil value with render_nil option
  # Add xsi:nil="true" attribute for W3C compliance
  if element.respond_to?(:xsi_nil) && element.xsi_nil
    attributes["xsi:nil"] = true
  end

  # Create element
  xml.create_and_add_element(tag_name, attributes: attributes,
                                       prefix: prefix) do |inner_xml|
    # Handle raw content (map_all directive)
    # If @raw_content exists, add as raw XML
    has_raw_content = false
    if element.respond_to?(:raw_content)
      raw_content = element.raw_content
      if raw_content && !raw_content.to_s.empty?
        inner_xml.add_xml_fragment(inner_xml, raw_content.to_s)
        has_raw_content = true
      end
    end

    # Skip text content and children if we have raw content
    unless has_raw_content
      # Add text content if present
      if element.text_content
        if element.cdata
          inner_xml.cdata(element.text_content.to_s)
        else
          inner_xml.text(element.text_content.to_s)
        end
      end

      # Recursively build child elements, passing namespace context
      element.children.each do |child|
        if child.is_a?(Lutaml::Xml::DataModel::XmlElement)
          build_xml_element(inner_xml, child,
                            parent_uses_default_ns: this_element_uses_default_ns,
                            parent_element_form_default: this_element_form_default,
                            parent_namespace_class: element_ns_class)
        elsif child.is_a?(String)
          inner_xml.text(child)
        end
      end
    end
  end
end

#build_xml_element_with_plan(xml, xml_element, plan, _options = {}) ⇒ Object

Build XML from XmlDataModel::XmlElement using DeclarationPlan tree (PARALLEL TRAVERSAL)

Uses moxml APIs exclusively — no native ::Oga::XML::* classes.

Parameters:

  • xml (Builder)

    XML builder (provides document access)

  • xml_element (XmlDataModel::XmlElement)

    Element content

  • plan (DeclarationPlan)

    Declaration plan with tree structure

  • options (Hash)

    Serialization options



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 459

def build_xml_element_with_plan(xml, xml_element, plan, _options = {})
  moxml_doc = xml.doc

  root_element = build_moxml_node(xml_element, plan.root_node,
                                  plan.global_prefix_registry,
                                  moxml_doc, plan: plan)
  moxml_doc.root = root_element

  # Add processing instructions before the root element.
  # reverse_each + add_previous_sibling maintains original order.
  xml_element.processing_instructions.reverse_each do |pi|
    pi_node = moxml_doc.create_processing_instruction(pi.target,
                                                      pi.content)
    root_element.add_previous_sibling(pi_node)
  end
end

#handle_nested_elements_with_plan(xml, value, rule, attribute, plan, options, parent_plan: nil) ⇒ Object

Handle nested model elements with plan



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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 604

def handle_nested_elements_with_plan(xml, value, rule, attribute, plan,
    options, parent_plan: nil)
  element_options = options.merge(
    rule: rule,
    attribute: attribute,
    tag_name: rule.name,
    mapper_class: attribute.type(register), # Override with child's type
  )

  if value.is_a?(Lutaml::Model::Collection)
    items = value.collection
    attr_type = attribute.type(register)

    if attr_type <= Lutaml::Model::Type::Value
      # Simple types - use add_simple_value for each item
      items.each do |val|
        xml_mapping = options[:mapper_class]&.mappings_for(:xml)
        add_simple_value(xml, rule, val, attribute, plan: parent_plan,
                                                    mapping: xml_mapping, options: options)
      end
    else
      # Model types - build elements with plans
      items.each do |val|
        # For polymorphic collections, use each item's actual class
        item_mapper_class = if polymorphic_value?(attribute, val)
                              val.class
                            else
                              attribute.type(register)
                            end

        # CRITICAL: Collect and plan for each item individually
        item_mapping = item_mapper_class.mappings_for(:xml)
        if item_mapping
          collector = NamespaceCollector.new(register)
          item_needs = collector.collect(val, item_mapping)

          planner = DeclarationPlanner.new(register)
          item_plan = planner.plan(val, item_mapping, item_needs,
                                   parent_plan: parent_plan, options: options)
        else
          item_plan = plan
        end

        item_options = element_options.merge(mapper_class: item_mapper_class)
        build_element_with_plan(xml, val, item_plan, item_options)
      end
    end
    return
  end

  case value
  when Array
    value.each do |val|
      # For polymorphic arrays, use each item's actual class
      item_mapper_class = if polymorphic_value?(attribute, val)
                            val.class
                          else
                            attribute.type(register)
                          end

      # CRITICAL: Collect and plan for each array item individually
      item_mapping = item_mapper_class.mappings_for(:xml)
      if item_mapping
        collector = NamespaceCollector.new(register)
        item_needs = collector.collect(val, item_mapping)

        planner = DeclarationPlanner.new(register)
        item_plan = planner.plan(val, item_mapping, item_needs,
                                 parent_plan: parent_plan, options: options)
      else
        item_plan = plan
      end

      item_options = element_options.merge(mapper_class: item_mapper_class)
      if item_plan
        build_element_with_plan(xml, val, item_plan, item_options)
      else
        build_element(xml, val, item_options)
      end
    end
  else
    build_element_with_plan(xml, value, plan, element_options)
  end
end

#orderObject



833
834
835
836
837
838
839
840
841
842
843
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 833

def order
  children.filter_map do |child|
    if child.text?
      next if child.text.nil? || child.text.strip.empty?

      Element.new("Text", "text", text_content: child.text)
    else
      Element.new("Element", child.unprefixed_name)
    end
  end
end

#to_xml(options = {}) ⇒ 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
73
74
75
76
77
78
79
80
81
82
83
84
85
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
# File 'lib/lutaml/xml/adapter/oga_adapter.rb', line 39

def to_xml(options = {})
  builder_options = {}
  encoding = determine_encoding(options)
  builder_options[:encoding] = encoding if encoding

  builder = Builder::Oga.build(builder_options) do |xml|
    if @root.is_a?(Oga::Element)
      @root.build_xml(xml)
    elsif @root.is_a?(Lutaml::Xml::DataModel::XmlElement)
      # XmlDataModel MUST go through Three-Phase Architecture
      mapper_class = options[:mapper_class] || @root.class
      xml_mapping = mapper_class.mappings_for(:xml)

      # Phase 1: Collect namespace needs from XmlElement tree
      collector = NamespaceCollector.new(register)
      needs = collector.collect(@root, xml_mapping,
                                mapper_class: mapper_class)

      # Phase 2: Plan namespace declarations with hoisting
      planner = DeclarationPlanner.new(register)
      plan = planner.plan(@root, xml_mapping, needs,
                          options: options)

      # Phase 3: Build with plan (TREE-BASED for XmlElement)
      build_xml_element_with_plan(xml, @root, plan, options)
    else
      # THREE-PHASE ARCHITECTURE
      mapper_class = options[:mapper_class] || @root.class
      xml_mapping = mapper_class.mappings_for(:xml)

      # Check if model has map_all with custom methods
      # Custom methods work with model instances, not XmlElement trees
      has_custom_map_all = xml_mapping.raw_mapping&.custom_methods &&
        xml_mapping.raw_mapping.custom_methods[:to]

      if has_custom_map_all
        # Use legacy path for custom methods
        collector = NamespaceCollector.new(register)
        needs = collector.collect(@root, xml_mapping,
                                  mapper_class: mapper_class)

        planner = DeclarationPlanner.new(register)
        plan = planner.plan(@root, xml_mapping, needs, options: options)

        build_element_with_plan(xml, @root, plan, options)
      else
        # Step 1: Transform model to XmlElement tree
        transformation = mapper_class.transformation_for(:xml, register)
        xml_element = transformation.transform(@root, options)

        # Step 2: Collect namespace needs from XmlElement tree
        collector = NamespaceCollector.new(register)
        needs = collector.collect(xml_element, xml_mapping,
                                  mapper_class: mapper_class)

        # Step 3: Plan declarations (builds ElementNode tree)
        planner = DeclarationPlanner.new(register)
        plan = planner.plan(xml_element, xml_mapping, needs,
                            options: options)

        # Step 4: Render using tree (NEW - parallel traversal)
        build_xml_element_with_plan(xml, xml_element, plan, options)
      end
    end
  end
  xml_data = builder.to_xml

  result = ""
  # Use DeclarationHandler methods instead of Document#declaration
  # Include declaration when encoding is specified OR when declaration is requested
  if (options[:encoding] && !options[:encoding].nil?) || options[:declaration]
    result += generate_declaration(options)
  end

  # Add DOCTYPE if present - use DeclarationHandler method
  doctype_to_use = options[:doctype] || @doctype
  if doctype_to_use && !options[:omit_doctype]
    result += generate_doctype_declaration(doctype_to_use)
  end

  result += xml_data

  # Encode result to desired encoding (Oga outputs UTF-8 by default)
  if encoding && encoding != Encoding::UTF_8
    result = result.encode(encoding)
  end

  result
end