Class: Lutaml::Lml::Executor::XmlAdapter
- Inherits:
-
Object
- Object
- Lutaml::Lml::Executor::XmlAdapter
- Extended by:
- AdapterHelpers
- Defined in:
- lib/lutaml/lml/executor/xml_adapter.rb
Overview
XML format adapter. Reads XML files and maps elements to hydrated compiled-class instances, and writes instances back to XML.
Registered for format “xml” via FormatAdapter::BUILTIN_ADAPTERS.
Element-to-attribute mapping is provided by the lutaml-model XML mapping generated on each compiled class by ModelCompiler. This adapter only selects which XML elements correspond to records (via the ‘where` XPath from the import definition) and hands each one to `target_class.from_xml` for deserialization.
Import shape (from LML ‘import { xml “…” { map_to X; where “/y” } }`):
- imp.file = path to XML file
- imp.attributes = TopElementAttribute list including:
map_to: TargetClass (compiled-class key)
where: XPath selector for each record element
Export shape (from LML ‘export { format xml { file “…”; root “X” } }`):
- exp.attributes = TopElementAttribute list including:
file: output path
root: root tag name (defaults to compiled class name)
indent: "true" / "false" (default true)
encoding: encoding string (default UTF-8)
Constant Summary collapse
- DEFAULT_ENCODING =
"UTF-8"- DEFAULT_SELECTOR =
"/*/*"- DEFAULT_ROOT_SUFFIX =
"s"
Class Method Summary collapse
-
.export(exp, instances, compiled:) ⇒ Object
Write instances to an XML file.
-
.import(imp, compiled:) ⇒ Object
Read an XML file and map elements to compiled-class instances.
Methods included from AdapterHelpers
attribute_value, find_attribute, find_class_for_instance, resolve_target_class
Class Method Details
.export(exp, instances, compiled:) ⇒ Object
Write instances to an XML file.
60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/lutaml/lml/executor/xml_adapter.rb', line 60 def export(exp, instances, compiled:) return if instances.empty? path = attribute_value(exp.attributes, "file") return unless path && !path.empty? class_name, target_class = find_class_for_instance(instances.first, compiled) return unless target_class = (exp, class_name) File.write(path, build_export_xml(instances, )) end |
.import(imp, compiled:) ⇒ Object
Read an XML file and map elements to compiled-class instances. Returns an array of hydrated objects.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/lutaml/lml/executor/xml_adapter.rb', line 41 def import(imp, compiled:) return [] unless imp.file return [] unless imp.attributes&.any? target_class = resolve_target_class(imp.attributes, compiled) return [] unless target_class path = imp.file return [] unless File.exist?(path) doc = Moxml.parse(File.read(path)) selector = attribute_value(imp.attributes, "where") || DEFAULT_SELECTOR doc.xpath(selector).map do |element| target_class.from_xml(element.to_xml) end end |