Thursday, 8 May 2014

Mirth Connect - Splitting a combined XML file into individual XML messages


Here is a solution to a problem to a Mirth Connect problem I had, which took me several hours to work out.

The problem I had was that I was using a File Reader import a large XML file with  hundreds of records in the following format:

 <employees>
    <employee>
      <employeeNumber>12345</employeeNumber>
      <surname>One</surname>
      <firstname>Number</firstname>
      <gender>F</gender>
    </employee>
    <employee>
      <employeeNumber>54321</employeeNumber>
      <surname>Two</surname>
      <firstname>Number</firstname>
      <gender>F</gender>
    </employee>
    <employee>
      <employeeNumber>99999</employeeNumber>
      <surname>Three</surname>
      <firstname>Number</firstname>
      <gender>F</gender>
    </employee>
  </employees>

I needed to break these up into individual messages to post on to a web service:

Message 1:

    <employee>
      <employeeNumber>12345</employeeNumber>
      <surname>One</surname>
      <firstname>Number</firstname>
      <gender>F</gender>
    </employee>

Message 2:

    <employee>
      <employeeNumber>54321</employeeNumber>
      <surname>Two</surname>
      <firstname>Number</firstname>
      <gender>F</gender>
    </employee>

Message 3:

    <employee>
      <employeeNumber>99999</employeeNumber>
      <surname>Three</surname>
      <firstname>Number</firstname>
      <gender>F</gender>
    </employee>

Initially, I though this would be a straightforward task, enabling the batch process option. However this is not supported with XML. I then moved on to using a 'for each in' loop, which seemed to be the preferred approach in Mirth forum, but I couldn't get the code to iterate properly.

Eventually, I configured a two channel approach. The first channel imports and splits the XML, the second receives the split messages, and performs the transformations and onward delivery.

A simple prototype can be configured as follows:

Step 1 create 2 channels as follows:.

1 - Channel name: XMLreceiver (or whatever you like)

Source: File Reader
Source Transformer: Create a new JavaScript step as follows:




Code:

empLength = (msg.employees.employee.length());  // This returns the number of <employee> elements

for (var i = 0; i < empLength; i++) {
// loop through the <employee> elements. Send the contents to the channel XMLsender
router.routeMessage('XMLsender',msg.employees.employee[i].toString());

}

Destination: Leave it as it is. The Source will route the message onto the second channel. 

2 - Channel name: XMLsender (or whatever you like, but it has to match the value in the routeMessage in the Source Transformer)

Source: Leave as it is. Messages will be routed in from your XMLsender channel.

Transformations and Destinations. Configure as for your receiving system, such as conversion to HL7.


No comments:

Post a Comment