title: Parsing HL7 v2 and converting to JSON/XML
body: <p>I need to process the content of <strong>HL7 v2.5 (OUL_R22) messages</strong> (scale: 10⁶ single messages and more) using python. To do so, I'm parsing the HL7 messages. At first I was using the python package <strong>HL7apy</strong> to convert to JSON (see <a href="https://stackoverflow.com/questions/40152674/hl7-to-json-conversition">Stack: HL7 to JSON conversition</a>). The output looks good, but some errors/bugs occurred while processing and it's really slow. So I tried out the java library <strong>HAPI</strong> to convert to XML (see <a href="https://stackoverflow.com/questions/32174102/converting-hl7-v2-to-json">Stack: Converting HL7 v2 to JSON</a>). The XML files can be read as dict using the package <strong>xmltodict</strong>. Compared to HL7apy the conversion is 50 times faster. But the structure of the output is inconsistent/heterogeneous. HAPI somehow wraps segments into new groups like <strong>OUL_R22.SPECIMEN / .ORDER / .RESULT</strong>. The question is: </p>
  
  <p>Can <strong>HAPI</strong> produce a flat output or an array which has a length equal to the unique occurrences of segments of the input? Or can you just add a "keep original structure" somewhere?</p>
  
  <hr>
  
  <p>To make things clearer: I need to process the content of the OBX-segment. </p>
  
  <p>The input would look like this:</p>
  
  <pre><code>MSH|...
  PID|...
  PV1|...
  SPM|...
  OBR|...
  ORC|...
  NTE|...
  NTE|...
  TQ1|...
  OBX|...
  OBX|...
  ...
  </code></pre>
  
  <p>The structure of the output looks like this (as XML of course):</p>
  
  <pre><code>OUL_R22
      MSH
      OUL_R22.PATIENT
      OUL_R22.VISIT
      OUL_R22.SPECIMEN
          OUL_R22.ORDER
              OUL_R22.TIMING_QTY
                  ...
              OUL_R22.RESULT
                  OBX
              OUL_R22.RESULT
                  OBX
  </code></pre>
  
  <p>Sometimes it's like this:</p>
  
  <pre><code>OUL_R22
      ...
      OBX
  </code></pre>
  
  <p>Or like this:</p>
  
  <pre><code>OUL_R22
      ...
      OUL_R22.SPECIMEN
          OBX
  </code></pre>
  
  <p>This is really inconsistent.</p>
  
  <hr>
  
  <p>What I want is something like this:</p>
  
  <pre><code>OUL_R22
      MSH
      PID
      ...
      OBX
  </code></pre>
  
  <p>Or like this:</p>
  
  <pre><code>[
      {
          "MSH": [],
          "PID": [],
          ...
          "OBX": [],
          ...
  </code></pre>