Programmatically schema validating an XML file in a BizTalk pipeline

In our BizTalk 2010 solution, we needed to programmatically validate an XML message in our receive pipeline. Our pipeline is fairly customized, and we found it most convenient to perform this validation as a part of the “Disassemble” step.

We use BizTalk’s XmlValidator component and the standard .NET XmlReader, thereby maintaining a data streams approach to avoid loading entire XML documents into RAM.

Without further ado:

/// Validate "pInMsg" against "schema".
/// If validation fails, this method throws XmlSchemaException or XmlSchemaValidationException with a description of the first error it encounters.
private static void ValidateXmlMessageAgainstSchema(IPipelineContext pContext, IBaseMessage pInMsg, SchemaWithNone schema)
XmlValidator xmlVal = new XmlValidator();
SchemaList sl = new SchemaList();
xmlVal.DocSpecNames = sl;
var validatedMsg = xmlVal.Execute(pContext, pInMsg);

validatedMsg.BodyPart.GetOriginalDataStream().Seek(0, SeekOrigin.Begin);
//The following two lines cause an exception to be thrown if the XML does not validate against the schema
//Create() only validates the first ~4000 bytes of the file. Read() validates all of it.
XmlReader xmlRead = XmlReader.Create(validatedMsg.BodyPart.GetOriginalDataStream());
while (xmlRead.Read());

This performs well; on our machine it processes a 20 MB file in a about a second or two. Exceptions contain good info complete with line numbers and positions.

PS – if you are encountering a “Root element is missing” exception while processing an XML stream in your pipeline, it may be because you are pointing an XML parser to a stream that has been read from without being reset afterwards.

Reset your streams to avoid this problem:

pInMsg.BodyPart.GetOriginalDataStream().Seek(0, SeekOrigin.Begin);

One response to “Programmatically schema validating an XML file in a BizTalk pipeline

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s