Module: FHIR::ClassXml
Instance Method Summary collapse
- #from_xml(xml) ⇒ Object
- #valid?(xml) ⇒ Boolean
- #validate(xml) ⇒ Object
- #xml_node_to_hash(node) ⇒ Object
Instance Method Details
#from_xml(xml) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/fhir_models/bootstrap/xml.rb', line 4 def from_xml(xml) doc = Nokogiri::XML(xml) doc.root.add_namespace_definition('f', 'http://hl7.org/fhir') doc.root.add_namespace_definition('x', 'http://www.w3.org/1999/xhtml') hash = xml_node_to_hash(doc.root) resource = nil begin resource_type = doc.root.name klass = versioned_fhir_module.const_get(resource_type) resource = klass.new(hash) rescue StandardError => e FHIR.logger.error("Failed to deserialize XML:\n#{e.backtrace}") FHIR.logger.debug("XML:\n#{xml}") resource = nil end resource end |
#valid?(xml) ⇒ Boolean
61 62 63 |
# File 'lib/fhir_models/bootstrap/xml.rb', line 61 def valid?(xml) validate(xml).empty? end |
#validate(xml) ⇒ Object
65 66 67 68 69 70 |
# File 'lib/fhir_models/bootstrap/xml.rb', line 65 def validate(xml) defns = File. '../definitions/schema', File.dirname(File.absolute_path(__FILE__)) schema = File.join(defns, 'fhir-all.xsd') xsd = Nokogiri::XML::Schema(File.new(schema)) xsd.validate(Nokogiri::XML(xml)) end |
#xml_node_to_hash(node) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/fhir_models/bootstrap/xml.rb', line 23 def xml_node_to_hash(node) hash = {} node.children.each do |child| next if [Nokogiri::XML::Text, Nokogiri::XML::Comment].include?(child.class) key = child.name if node.name == 'text' && key == 'div' hash[key] = child.to_xml else value = child.get_attribute('value') if value.nil? && !child.children.empty? value = xml_node_to_hash(child) end if hash[key] hash[key] = [hash[key]] unless hash[key].is_a?(Array) hash[key] << value else hash[key] = value end end end hash['url'] = node.get_attribute('url') if ['extension', 'modifierExtension'].include?(node.name) hash['id'] = node.get_attribute('id') if node.get_attribute('id') # Testscript fixture ids (applies to any BackboneElement) hash['resourceType'] = node.name if versioned_fhir_module::RESOURCES.include?(node.name) # If this hash contains nothing but an embedded resource, we should return that # embedded resource without the wrapper if hash.keys.length == 1 && versioned_fhir_module::RESOURCES.include?(hash.keys.first) && hash.values.first.is_a?(Hash) && hash.values.first['resourceType'] == hash.keys.first hash.values.first else hash end end |