nazrulworld / fhir.resources

FHIR Resources https://www.hl7.org/fhir/resourcelist.html
https://pypi.org/project/fhir.resources/
Other
365 stars 104 forks source link

Question: best way in code to parse a variety of resources? #106

Open ArdonToonstra opened 2 years ago

ArdonToonstra commented 2 years ago

Description

How to efficiently parse resource instances into their suitable python classes?

What I Did

I have a bunch of XML instances that I am trying to parse. I got it working by first checking the XML root and then parsing it to the correct class like the snippet below. This, however, results in a lot of lines of code. Is there a more efficient way?

if root.tag == '{http://hl7.org/fhir}AllergyIntolerance':
        resource = AllergyIntolerance.parse_file(f)
    elif root.tag == '{http://hl7.org/fhir}CarePlan': 
        resource = CarePlan.parse_file(f)
    elif root.tag == '{http://hl7.org/fhir}Condition': 
        resource = Condition.parse_file(f)
    elif root.tag == '{http://hl7.org/fhir}Consent': 
        resource = Consent.parse_file(f)
ArdonToonstra commented 2 years ago

Update: I have now rewritten it to:

resource_name = root.tag.replace('{http://hl7.org/fhir}','') resource = import_from("fhir.resources." + resource_name.lower(), resource_name).parse_file(f)