class Lutaml::Model::XmlAdapter::OxAdapter
def self.parse(xml, options = {})
def self.parse(xml, options = {}) Ox.default_options = Ox.default_options.merge(encoding: options[:encoding] || "UTF-8") parsed = Ox.parse(xml) root = OxElement.new(parsed) new(root, Ox.default_options[:encoding]) end
def build_ordered_element(builder, element, options = {})
def build_ordered_element(builder, element, options = {}) mapper_class = options[:mapper_class] || element.class xml_mapping = mapper_class.mappings_for(:xml) return xml unless xml_mapping attributes = build_attributes(element, xml_mapping).compact tag_name = options[:tag_name] || xml_mapping.root_element builder.create_and_add_element(tag_name, attributes: attributes) do |el| index_hash = {} content = [] element.element_order.each do |name| index_hash[name] ||= -1 curr_index = index_hash[name] += 1 element_rule = xml_mapping.find_by_name(name) next if element_rule.nil? attribute_def = attribute_definition_for(element, element_rule, mapper_class: mapper_class) value = attribute_value_for(element, element_rule) next if element_rule == xml_mapping.content_mapping && element_rule.cdata && name == "text" if element_rule == xml_mapping.content_mapping text = element.send(xml_mapping.content_mapping.to) text = text[curr_index] if text.is_a?(Array) next el.add_text(el, text, cdata: element_rule.cdata) if element.mixed? content << text elsif !value.nil? || element_rule.render_nil? value = value[curr_index] if attribute_def.collection? add_to_xml( el, element, nil, value, options.merge( attribute: attribute_def, rule: element_rule, ), ) end end el.add_text(el, content.join) end end
def to_xml(options = {})
def to_xml(options = {}) builder_options = { version: options[:version] } builder_options[:encoding] = if options.key?(:encoding) options[:encoding] elsif options.key?(:parse_encoding) options[:parse_encoding] else "UTF-8" end builder = Builder::Ox.build builder.xml.instruct(:xml, encoding: options[:parse_encoding]) if @root.is_a?(Lutaml::Model::XmlAdapter::OxElement) @root.build_xml(builder) elsif ordered?(@root, options) build_ordered_element(builder, @root, options) else mapper_class = options[:mapper_class] || @root.class options[:xml_attributes] = build_namespace_attributes(mapper_class) build_element(builder, @root, options) end xml_data = builder.xml.to_s if builder_options[:encoding] && xml_data.valid_encoding? xml_data = xml_data.encode(builder_options[:encoding]) end stripped_data = xml_data.lines.drop(1).join options[:declaration] ? declaration(options) + stripped_data : stripped_data end