Announcement

Collapse
No announcement yet.

Working solution to validate a XML against a XSD

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Working solution to validate a XML against a XSD

    Hello,

    After creating a HL7 v3 channel, I was on the need to successfully validate an incoming HL7 v3 XML file against their XSD schema.
    So I searched and asked in this forum for a solution and one Mirth Employee refered here to a Java Package that could do XML validation. Based on that and this question on stackoverflow I implemented a solution for Mirth Connect.

    First you need to download JAXP, this is a Java API for XML Processing, and import the library into Mirth Connect.

    Then with this code you can validate an incoming XML message against a XSD file:

    Code:
    // open schema file
    var schemaFile = new Packages.java.io.File("path_to_xsd_file"); // like "C:\\hl7v3\\schema.xsd"
    // create a schema object
    var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    var schema = schemaFactory.newSchema(schemaFile);
    
    // Create a Reader from the incoming XML message
    var reader = new Packages.java.io.StringReader(messageObject.getRawData());
    
    // Acts as an holder for a transformation Source in the form of a stream of XML markup.
    var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(reader);
    
    // create a new validator for the schema
    var validator = schema.newValidator();
    
    try {
    	// validates the message
    	validator.validate(xmlFile);
    	// valid message
    	logger.info('valid');
    } catch (err) {
    	// invalid message
    	logger.error(err.toString());
    }
    I hope this helps all of you searching for a working solution.

    PS: Based that XML validation is essential to HL7 v3 messages, maybe this library could be included in future releases of Mirth Connect or create a native support to XML validation.
    Last edited by capzulu; 07-31-2013, 06:11 AM.

  • #2
    Nice job thanks for the post

    Thanks for the heads up on validating an XML.

    Comment


    • #3
      I'm able to load the xsd and validate the xml but, how does the message processing stop if there is a validation error in the xml? Do I need to throw a specific error or call a mirth function?

      I want to the message to stop processing and throw an "error" alert to the dashboard showing the message has failed.

      Comment


      • #4
        If the validation of the XML against the XSD fails, Mirth writes the error to the log window.

        This code does that
        Code:
        catch (err) {
        	// invalid message
        	logger.error(err.toString());
        }
        If you want the message processing to stop, you must use this when the validation fails.
        Code:
        return false;
        So you have
        Code:
        catch (err) {
        	// invalid message
        	logger.error(err.toString());
                return false;
        }
        Also, in the dashboard, i don't remember if it will increment the Filter or Error numbers.
        Last edited by capzulu; 11-06-2013, 02:01 PM.

        Comment


        • #5
          Thanks!! Looks like it increments the "filter" numbers, not error.

          Comment


          • #6
            Ok. Thanks for the information

            Comment


            • #7
              Validating the XML against the CCD XSD

              Hi ,

              I have tried to validate the same way you have described in this thread but I get a error :

              Failed to read schema document 'file:/C:/Program%20Files/Mirth%20Connect/UsersanshumanbDesktopCDA%20PROJECTCDA%20PROJECTsch ema.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.


              Not sure why this error is there , could you please help me on this.


              Thanks and Regards,

              Anky

              Comment


              • #8
                Hello Anky,

                It seems to me that the path to the XSD file is incorrect.

                To see if the problem is with the XSD file, use my example.
                Copy your file to a directory like c:\hl7v3\schema.xsd and then update this line
                Code:
                var schemaFile = new Packages.java.io.File("C:\\hl7v3\\schema.xsd");
                Test it and if the problems persists, then the problem is with your XSD file.

                Comment


                • #9
                  Error:messageObject not defined

                  I am getting an error of "messageObject" not defined when trying to use the above code to validate the xml against the xsd.

                  Any help would be appreciated.

                  SCRIPT SOURCE: TRANSFORMER
                  SOURCE CODE:
                  51: // create a schema object
                  52: var schemaFactory = Packages.javax.xml.validation.SchemaFactory.newIns tance("http://www.w3.org/2001/XMLSchema");
                  53: var schema = schemaFactory.newSchema(schemaFile);
                  54:
                  55: // Create a Reader from the incoming XML message
                  56: var reader = new Packages.java.io.StringReader(typeof messageObject.getRawData());
                  57:
                  58: // Acts as an holder for a transformation Source in the form of a stream of XML markup.
                  59: var xmlFile = new Packages.javax.xml.transform.stream.StreamSource(r eader);
                  60:
                  LINE NUMBER: 56
                  DETAILS: ReferenceError: "messageObject" is not defined.
                  at fb7ccbd7-64f0-4e38-9ece-3aa19742ae0a:56 (doTransform)
                  at fb7ccbd7-64f0-4e38-9ece-3aa19742ae0a:94 (doScript)
                  at fb7ccbd7-64f0-4e38-9ece-3aa19742ae0a:96
                  at com.mirth.connect.server.transformers.JavaScriptFi lterTransformer$FilterTransformerTask.doCall(JavaS criptFilterTransformer.java:154)
                  at com.mirth.connect.server.transformers.JavaScriptFi lterTransformer$FilterTransformerTask.doCall(JavaS criptFilterTransformer.java:119)
                  at com.mirth.connect.server.util.javascript.JavaScrip tTask.call(JavaScriptTask.java:113)
                  at java.util.concurrent.FutureTask.run(Unknown Source)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker( Unknown Source)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run (Unknown Source)
                  at java.lang.Thread.run(Unknown Source)

                  Comment


                  • #10
                    This original post is from 2013. I think you are on 3.0 and higher mirth version.
                    messageObject is deprecated now. To get the raw message use

                    connectorMessage.getRawData()
                    HL7v2.7 Certified Control Specialist!

                    Comment


                    • #11
                      Thank you for sharing the details. I have followed the steps and successfully validate the XML. However, I need to perform the below action on this:

                      Any validation error should route to the Destination 1. Whereas, valid message should go to the Destination 2.

                      May I know what kind of filter logic I need to use or any changes in the script?

                      I tried to change the return function but it is not stopping the message to process.

                      Comment


                      • #12
                        Something went horribly wrong with this post above!!
                        HL7v2.7 Certified Control Specialist!

                        Comment


                        • #13
                          Hi,

                          the XML validator works like a charm.

                          How can I set the Response Message in the transformer that the source Connector will receive under Connector -> Source -> Messages -> Response

                          Comment

                          Working...
                          X