Sunday, 14 May 2023

Manipulating XML Messages with C# in HL7 Soup’s Integration Host

Are you looking for a way to manipulate XML messages using HL7 Soup’s Integration Host using c#? Look no further! In this post, we’ll show you how to use the code below to do just that.

In this sample, we'll demonstrate with XDocument, but XmlDocument will work fine too.

First, make sure that the System.Xml.Linq.dll file is correctly referenced in your code. If you can’t find it, don’t worry - the code will still work, but you may see red squiggly lines in the editor. These can be ignored.

Next, get the destination message using the activityInstance.Message property. Then, load the incoming message into an XDocument object using System.Xml.Linq.XDocument.Parse().

From there, you can update the XML as needed. In our example, we add a new ValidFrom element to the root of the document. Once you’ve made your changes, get the updated XML using the ToString() method and set it as the new text for the root element.

Here’s the full code:

//Note, the next line might need redirecting to the file System.Xml.Linq.dll on your computer. 
//Another common location is C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.1\System.Xml.Linq.dll
//Even if you can't find it, don't worry. The code will still work, but you will just see red squiggly lines in the editor.  These can be ignored - it's only the editor that cannot find them.
#r "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Xml.Linq.dll"

//Get the destination message
var destinationMessage = activityInstance.Message; //Use IHL7Message for HL7 Messages and IMessage for other message types

string xmlIn = workflowInstance.ReceivingActivityInstance.Message.Text;
workflowInstance.SetVariable("xmlIn",xmlIn); //put into variable to help debugging.  Remove once working

//Load incoming message into an XDocument object
System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Parse(xmlIn);

//Update as you see fit.
doc.Root.Add(new System.Xml.Linq.XElement("ValidFrom", "2021-06-25T11:45:22Z"));

//Get the updated XML
string xmlString = doc.ToString();

workflowInstance.SetVariable("xmlOut",xmlString);//put into variable to help debugging.  Remove once working

//Set the root element to be the new XML text.
destinationMessage.SetStructureAtPath("Patient",xmlString); 

We hope this helps you manipulate XML messages with HL7 Soup’s Integration Host! Let us know if you have any questions or comments.