Thursday 16 March 2023

Remove multiple segments from an HL7 message with HL7 Soup

 If you're working with HL7 messages, you may need to remove multiple segments from a message.

However, if you do it in a loop, you find that only the first item is removed.  This is because the delete causes the message to be recreated, and all remaining segments in the loop reference a different message instance.

Try this instead:

//Get the current message we are writing as an HL7 Message
IHL7Message destinationMessage = (IHL7Message)activityInstance.Message; 

//Get all the IN1 Sgments
var in1 = destinationMessage.GetSegments("IN1");

//Set BeginUpdate as we are updating multiple Segments and don't want our list to change until we complete
destinationMessage.BeginUpdate();

//Loop over all the IN1 segments
foreach (var seg in in1)
{
      //remove the individual Segment  
      destinationMessage.RemoveSegment(seg);
}

//Update the message
destinationMessage.EndUpdate();

The above example removes all the IN1 segments from an HL7 message. The code first gets the current message as an HL7 message and then gets all the IN1 segments. It then sets BeginUpdate as it is updating multiple segments and doesn’t want the list to change until it completes. It then loops over all the IN1 segments and removes the individual segment. Finally, it updates the message.

No comments:

Post a Comment