Introduction

The project makes use of a class written by T. Clark to execute the actual conversion, I found the project containing this very useful class located here on the Code Project website: http://www.codeproject.com/Articles/29670/Converting-HL7-to-XML. The application included here takes this class and wraps it up in a Windows Form application. This application allows the user to open up the HL7 message in raw format, uses T. Clark's class to convert it to XML, and then displays the XML in a tree view control. The application also provides the means to save the XML file as a true XML document and, based upon a query of the derived XML, sets the default file name to the message control ID associated with the raw HL7 document.

Fake-HL7-Message.jpg
Figure 1: Application Displaying a Fake HL7 Message in a Tree View

Getting Started

Download and unzip the attached project to get started. Open the project up into Visual Studio 2012 and review its contents. In general you will find a Windows Forms application with a main application form cleverly entitled, "Form1.cs". There is also an about box listed as, "AboutApp.cs". Aside from the two forms, there is a single class, "HL7ToXmlConverter.cs" that wraps up the class written by T. Clark and mentioned earlier in the article.

The main form contains the code necessary to open the raw files, convert the files to XML using Clark's class, and to then save the raw HL7 messages having been converted into true XML format. The conversion has worked flawlessly with the HL7 messages I have encountered but you may need to alter the conversion class if you have any problems working with different sources for the raw HL7 messages.

The Code: ConvertHL7ToXml Class

As was mentioned, this class was written by a T. Clark and is sited from the URL provided previously. Clark has annotated his code and you may open the class and read that annotation to study the approach used to handle the conversion.

The Code: Form1 Class

This class puts Clark's conversion class into the context of a Windows Form based application. This form allows the user to open up the raw (non-XML format) HL7 messages (which oddly enough carry the .xml extension). Once opened and converted to XML, the class temporarily stores the true XML file, and then displays the XML document in a tree view control as is shown in Figure 1 of this document. The class also allows the user to save the file in proper XML format to the file system; in so doing, the code queries the XML document to obtain the message control ID and uses that message control ID as the default file name. The system I am using now initially saves the HL7 messages using a GUID as the file name, this GUID does not identify the records in any meaningful way and it makes evaluating message errors more difficult as finding the file needed cannot be accomplished using the GUID file name. The GUID provided as a file name never appears in any part of the message itself and therefore it is never captured nor stored into the database built from the messages; at that, if you wish to look at the raw message.

The code for the entire class is presented below; it is annotated to describe the purpose of each part of the code:

using System;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using
System.Xml.XPath;

Code
namespace ConvertHL7ToXml
{
Code
    public partial class Form1 : Form
Code
    {
Code
        // the file to be converted; this is the HL7 message in its raw format; even
Code
        // though it uses an xml file extension, is it not xml but rather is a
Code
        // pipe and character delimited file with a specific definition
Code
        String sourceFilePath;
Code
Code
        // a temporary place to save the file after it is converted to true xml format
Code
        String tempFilePath;
Code
Code
        // the actual xml document to be
Code
        XmlDocument doc = new XmlDocument();
Code
Code
        /// <summary>
Code
        /// Constructor
Code
        /// </summary>
Code
        public Form1()
Code
        {
Code
            InitializeComponent();
Code
Code
            // define the temporary xml file storage path
Code
            tempFilePath = Application.StartupPath + "\\temp.xml";
Code
        }
Code
Code
Code
        /// <summary>
Code
        /// Exit the application
Code
        /// </summary>
Code
        /// <param name="sender"></param>
Code
        /// <param name="e"></param>
Code
        private void ExitToolStripMenuItemClick(object sender, EventArgs e)
Code
        {
Code
            Application.Exit();
Code
        }
Code
Code
Code
        /// <summary>
Code
        /// Open an existing HL7 message file and convert it to actual XML,
Code
        /// Then display the document in a tree view
Code
        /// </summary>
Code
        /// <param name="sender"></param>
Code
        /// <param name="e"></param>
Code
        private void OpenToolStripMenuItemClick(object sender, EventArgs e)
Code
        {
Code
            try
Code
            {
Code
                // define the open file dialog, since HLy messages are saved with
Code
                // an xml extension (even though they are not xml) we will set up
Code
                // the dialog to allow the user to open a file with that extension
Code
                openFileDialog1.Title = "Open HL7 Message File";
Code
                openFileDialog1.Filter = "XML Files|*.xml";
Code
                openFileDialog1.DefaultExt = "XML";
Code
                openFileDialog1.FileName = string.Empty;
Code
Code
                // or you can use the dialog result
Code
                openFileDialog1.ShowDialog();
Code
Code
                // make sure we get a file name
Code
                if (String.IsNullOrEmpty(openFileDialog1.FileName))
Code
                    return;
Code
Code
                // set the file path member variable
Code
                sourceFilePath = openFileDialog1.FileName;
Code
Code
                // read the contents of the file into a stream reader
Code
                StreamReader sr = new StreamReader(sourceFilePath);
Code
                string hl7Message = sr.ReadToEnd();
Code
                sr.Close();
Code
Code
                // define a string to hold the xml returned from the convert to xml call,
Code
                // refer to the HL7ToXmlConverter class by T. Clark for details on how
Code
                // the conversion works
Code
                string xmlFileContents = HL7ToXmlConverter.ConvertToXml(hl7Message);
Code
Code
                // save the returned XML into a temporary xml file for now, then we can
Code
                // work with the xml to get it displayed in the treeview
Code
                using (StreamWriter outfile = new StreamWriter(tempFilePath))
Code
                {
Code
                    outfile.Write(xmlFileContents);
Code
                }
Code
Code
Code
                // Clear out the treeview in case it has another xml file displayed in it
Code
                treeXml.Nodes.Clear();
Code
Code
                // set the wait cursor
Code
                this.Cursor = Cursors.WaitCursor;
Code
Code
                // create a new xml doc
Code
                XmlDocument doc = new XmlDocument();
Code
Code
                try
Code
                {
Code
                    // load the xml doc from the temporary xml file
Code
                    doc.Load(tempFilePath);
Code
Code
                    // set the form text to display the file name
Code
                    this.Text = "File - " + tempFilePath;
Code
Code
                    // return the cursor to normal
Code
                    this.Cursor = Cursors.Default;
Code
                }
Code
                catch (Exception ex1)
Code
                {
Code
                    // return the cursor to normal
Code
                    this.Cursor = Cursors.Default;
Code
Code
                    // and describe the error to the user
Code
                    MessageBox.Show(ex1.Message, "Error Opening File");
Code
Code
                    // since we had an error, don't try to display the file
Code
                    // in the treeview
Code
                    return;
Code
                }
Code
Code
                // open the xml doc into the treeview for inspection
Code
                PushToTreeView(doc, treeXml.Nodes);
Code
Code
                // open all the nodes after the treeview is populated
Code
                treeXml.ExpandAll();
Code
Code
                // restore the cursor to normal
Code
                this.Cursor = Cursors.Default;
Code
Code
            }
Code
            catch (Exception ex2)
Code
            {
Code
                // describe what went wrong in the event of an error
Code
                MessageBox.Show(ex2.Message, "Unable to Open the Document");
Code
            }
Code
        }
Code
Code
Code
        /// <summary>
Code
        /// Save the current open file as an xml document
Code
        /// </summary>
Code
        /// <param name="sender"></param>
Code
        /// <param name="e"></param>
Code
        private void SaveToolStripMenuItemClick(object sender, EventArgs e)
Code
        {
Code
            // configure the save file dialog to allow the user to save an xml file
Code
            saveFileDialog1.Title = "Save XML File";
Code
            saveFileDialog1.Filter = "XML Files|*.xml";
Code
            saveFileDialog1.DefaultExt = "XML";
Code
Code
            // leave the initial file name as an empty string, we
Code
            // will replace that with the message control ID in
Code
            // a minute but we will give the user the option of saving it
Code
            // with a name of their choice
Code
            saveFileDialog1.FileName = string.Empty;
Code
Code
            // load the temporary xml document into an instance of
Code
            // the XML document we defined with class scope
Code
            doc.Load(tempFilePath);
Code
Code
            // create a navigator so we can find the message control ID and use that
Code
            // as the initial file name
Code
            XPathNavigator navigator = doc.CreateNavigator();
Code
Code
            // the message control ID is stored in the message header in the
Code
            // 9th position
Code
            string searchTerm = "//MSH/MSH.9";
Code
Code
            // look for the node indicated in the search term
Code
            XPathNodeIterator nodes = navigator.Select(searchTerm);
Code
Code
            // iterate through the nodes to find the value in the
Code
            // selected node - should be one only
Code
            while (nodes.MoveNext())
Code
            {
Code
                // create an instance of a node from the
Code
                // selected node
Code
                XPathNavigator node = nodes.Current;
Code
Code
                // set the default file name to the value stored in the
Code
                // selected node
Code
                saveFileDialog1.FileName = node.InnerXml;
Code
            }
Code
Code
            // open the dialog and get the user's OK
Code
            DialogResult result = saveFileDialog1.ShowDialog();
Code
Code
            if (result == System.Windows.Forms.DialogResult.OK)
Code
            {
Code
                // copy the temporary file to the new location and rename it
Code
                // using the message control ID scraped from the xml document
Code
                System.IO.File.Move(tempFilePath, saveFileDialog1.FileName);
Code
            }
Code
        }
Code
Code
Code
        /// <summary>
Code
        /// Show about box
Code
        /// </summary>
Code
        /// <param name="sender"></param>
Code
        /// <param name="e"></param>
Code
        private void AboutConvertToTrueXmlToolStripMenuItemClick(object sender,
Code
         EventArgs e)
Code
        {
Code
            AboutApp f = new AboutApp();
Code
            f.ShowDialog();
Code
        }
Code
Code
Code
        /// <summary>
Code
        /// Populate the tree view using the xml obtained using T. Clark's xml converter class
Code
        /// </summary>
Code
        /// <param name="currentNode"></param>
Code
        /// <param name="nodCollection"></param>
Code
        private void PushToTreeView(XmlNode currentNode, TreeNodeCollection
Code
         nodCollection)
Code
        {
Code
            TreeNode insertNode = nodCollection.Add(currentNode.Name);
Code
Code
            switch (currentNode.NodeType)
Code
            {
Code
                case XmlNodeType.Element:
Code
                    insertNode.Text = currentNode.Name;
Code
                    insertNode.Tag = "Element";
Code
                    insertNode.ImageIndex = 1;
Code
                    break;
Code
                case XmlNodeType.Attribute:
Code
                    insertNode.Text = "@" + currentNode.Name;
Code
                    insertNode.Tag = "Attribute";
Code
                    insertNode.ImageIndex = 2;
Code
                    break;
Code
                case XmlNodeType.Text:
Code
                    insertNode.Text = currentNode.Value;
Code
                    insertNode.Tag = "Text";
Code
                    insertNode.ImageIndex = 3;
Code
                    break;
Code
                case XmlNodeType.CDATA:
Code
                    insertNode.Text = currentNode.Value;
Code
                    insertNode.Tag = "CDATA";
Code
                    insertNode.ImageIndex = 4;
Code
                    break;
Code
                case XmlNodeType.Comment:
Code
                    insertNode.Text = currentNode.Value;
Code
                    insertNode.Tag = "Comment";
Code
                    insertNode.ImageIndex = 5;
Code
                    break;
Code
                case XmlNodeType.Entity:
Code
                    insertNode.Text = currentNode.Value;
Code
                    insertNode.Tag = "Entity";
Code
                    insertNode.ImageIndex = 6;
Code
                    break;
Code
                case XmlNodeType.Notation:
Code
                    insertNode.Text = currentNode.Value;
Code
                    insertNode.Tag = "Notation";
Code
                    insertNode.ImageIndex = 7;
Code
                    break;
Code
                default:
Code
                    break;
Code
            }
Code
Code
            // recursive processing
Code
Code
            // check the current node for attributes
Code
            if (currentNode.Attributes != null && currentNode.Attributes.Count > 0)
Code
            {
Code
                // write out the attributes to the treeview
Code
                foreach (XmlAttribute attribute in currentNode.Attributes)
Code
                {
Code
                    PushToTreeView(attribute, insertNode.Nodes);
Code
                }
Code
            }
Code
Code
            // check the current node for child nodes
Code
            if (currentNode.HasChildNodes)
Code
            {
Code
                // write out the child nodes to the treeview
Code
                foreach (XmlNode childNode in currentNode.ChildNodes)
Code
                {
Code
                    PushToTreeView(childNode, insertNode.Nodes);
Code
                }
Code
            }
Code
Code
        }
Code
    }
Code
}