module Lutaml::Model::Serialize::ClassMethods

def apply_xml_mapping(doc, instance, options = {})

def apply_xml_mapping(doc, instance, options = {})
  options = Utils.deep_dup(options)
  instance.encoding = options[:encoding]
  return instance unless doc
  if options[:default_namespace].nil?
    options[:default_namespace] =
      mappings_for(:xml)&.namespace_uri
  end
  mappings = options[:mappings] || mappings_for(:xml).mappings
  if doc.is_a?(Array)
    raise Lutaml::Model::CollectionTrueMissingError(self, option[:caller_class])
  end
  if instance.respond_to?(:ordered=) && doc.is_a?(Lutaml::Model::MappingHash)
    instance.element_order = doc.item_order
    instance.ordered = mappings_for(:xml).ordered? || options[:ordered]
    instance.mixed = mappings_for(:xml).mixed_content? || options[:mixed_content]
  end
  if doc["attributes"]&.key?("__schema_location")
    instance.schema_location = Lutaml::Model::SchemaLocation.new(
      schema_location: doc["attributes"]["__schema_location"][:schema_location],
      prefix: doc["attributes"]["__schema_location"][:prefix],
      namespace: doc["attributes"]["__schema_location"][:namespace],
    )
  end
  defaults_used = []
  mappings.each do |rule|
    raise "Attribute '#{rule.to}' not found in #{self}" unless valid_rule?(rule)
    attr = attribute_for_rule(rule)
    value = if rule.raw_mapping?
              doc.node.inner_xml
            elsif rule.content_mapping?
              doc[rule.content_key]
            elsif val = value_for_rule(doc, rule, options)
              val
            else
              defaults_used << rule.to
              attr&.default || rule.to_value_for(instance)
            end
    value = normalize_xml_value(value, rule, attr, options)
    rule.deserialize(instance, value, attributes, self)
  end
  defaults_used.each do |attribute_name|
    instance.using_default_for(attribute_name)
  end
  instance
end