I got this error when doing custom XSLT with a BizTalk map.

It was a case of “brain fog”. The proper keyword is xsl:choose, not xsl:case. Other languages call this a switch or a case. I just temporarily forgot that XSLT calls it a “choose”.

Example of what the xsl:choose looks like (from https://www.w3schools.com/xml/xsl_choose.asp

  <xsl:when test="expression">
    ... some output ...
    ... some output ....

This is a run-time error can occur when you use a map that is XSLT based. It is possible to compile and deploy the project, even when the XSLT is malformed or has errors in it.

Try to reproduce in the developer environment with one or both of the following:
1) Open your project in Visual Studio, and do a test map with some real incoming data.
2) Make sure you XSLT is well-formed XML.
3) You might also try validating the map (right-click validate)

I also saw this happen when I removed a “Logical Existence” functoid, and the an XSLT functoid was using it as follows:

			<xsl:variable name="var:v14A" select="userCSharp:LogicalExistence(boolean(L004))" />

By doing the “test map”, it gave the error:
Extension object ‘http://schemas.microsoft.com/BizTalk/2003/userCSharp’ does not contain a matching ‘LogicalExistence’ method that has 1 parameter(s).

Using the following Reg-Ex (Regular Expression) to find UTF-8 or UTF-16 characters in a text file;
this should work with any editor that supports Reg-Ex, such as NotePad++ or Visual Studio.

Be sure and check the “Regular Expression” option on the search, then type in the find string: [x80-xFF]


Exception: System.ServiceModel.CommunicationException: There was an error while trying to serialize parameter http://tempuri.org/:ExportValuationPolicyNumberResult. The InnerException message was ‘Type ‘TFBIC.RCT.WCFWebServices.ExpressLync.MainStreetValuation’ with data contract name ‘MainStreetValuation:http://schemas.datacontract.org/2004/07/TFBIC.RCT.WCFWebServices.ExpressLync’ is not expected. Add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.’. Please see InnerException for more details. —> System.Runtime.Serialization.SerializationException: Type ‘TFBIC.RCT.WCFWebServices.ExpressLync.MainStreetValuation’ with data contract name ‘MainStreetValuation:http://schemas.datacontract.org/2004/07/TFBIC.RCT.WCFWebServices.ExpressLync’ is not expected. Add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.


1. Manually create a proxy to the WCF Service from the command line like so:
svcutil /serializer:XmlSerializer http://localhost:46122/ValuationService.svc

2. Add the [XmlSerializerFormat] to your ServiceContract on the WCF Service

By doing this, we force our WCF Service to use the XmlSerializer rather than the default DataContractSerializer. Note: you?ll need to call the WCF service from you new proxy in your sample code.

Converts several date/time formats to standard XML Date/ Time

        /// <summary>
        /// This takes a vendor's non-standard dates, such as 5/1/2008 and formats as XML Date.
        /// (i.e. the month may one or two digits, the day may be one or two digits).
        /// Neal Walters - changed on 09/03/2008 to  throw exception. 
        /// also tested to make sure it handles all the following dates (and it does)
        ///    string testDate1 = "03/09/2008";
        ///    string testDate2 = "1999-05-31";
        ///    string testDate3 = "03/09/2008 10:50:16.157";
        ///    string testDate4 = "1999-05-31T13:20:00.000-05:00";
        ///    string testDate5 = "2008-09-03 10:50:16.157";
        ///    string testDate6 = "2008-09-32";
        /// </summary>
        /// <param name="inDate"></param>
        /// <returns></returns>
        public static string ConvertDateTimetoXmlDateTime(string inDate)
                DateTime dtIn = DateTime.Parse(inDate);
                return System.Xml.XmlConvert.ToString(dtIn, System.Xml.XmlDateTimeSerializationMode.Local);

                string errorMessage = "invalid-Date/Time-conversion from value='" + inDate + "'";
                throw new Exception(errorMessage);
                //return errorMessage;

This code builds an xml document in memory, then returns it as an System.Xml.XmlDocument. It also show the proper way to build an XML date.

        /// <summary>
        /// This routine is needed when an in-bound endpoint has a map failure when translating
        /// inbound schema to  TMXML. 
        /// </summary>
        /// <returns></returns>
        public static XmlDocument ReturnNewTMXML()
            DateTime currentDateTime = DateTime.Now;
            string strDateTime = currentDateTime.ToLongDateString();

            string strMyDoc =
            "<n2:MyRootEl xsi:schemaLocation='http://MyNamespace.MySchema.xsd' +
'xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
                "<source>" +
                  "<objectId>NULL</objectId>" +
                  "<objectType>NULL</objectType>" +
                  "<requestor>NULL</requestor>" +
                  "<transactionGuid>NULL</transactionGuid>" +
                  "<requestType>NULL</requestType>" +
                  "<dateTimeReceived>" + TFBIC.Common.BizTalk.Components.MapHelper.ConvertDateTimetoXmlDateTime(strDateTime) + "</dateTimeReceived>" +
                  "<isResponseExpected>false</isResponseExpected>" +
                "</source>" +

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true; //making sure no whitespaces get added
            return xmlDoc;


This sample shows how to build an XML node and add it as a new child in an existing

        /// <summary>
        /// This routine is needed when an in-bound endpoint Sends TMXML with no Itinerary Node in the Header
        /// The Receiver must make sure that the Itinerary node is present in the Header.
        /// </summary>
        /// <returns></returns>
        public static XmlDocument AddItineraryNode(XmlDocument xmlDoc)
            xmlDoc.PreserveWhitespace = true; //making sure no whitespaces get added
            string strXPath = "//*[local-name()='ItineraryStep']";
            string strItinerary =
                    "<policyName>NULL</policyName>" +
                     "<status>NULL</status>" +
                     "<currentStepName>NULL</currentStepName>" +
                     "<currentStepStatus>NULL</currentStepStatus>" +
                     "<currentStepIndex>0</currentStepIndex>" +
                     "<currentStepErrorType>NULL</currentStepErrorType>" +
                     "<currentProcessCode>NULL</currentProcessCode>" +
                     "<currentProcessMethod>NULL</currentProcessMethod>" +
            XmlNamespaceManager iMgr = new XmlNamespaceManager(xmlDoc.NameTable);
            XmlNode nodeItin = xmlDoc.SelectSingleNode(strXPath, iMgr);

            if (nodeItin == null)
                XmlElement newItinerary = xmlDoc.CreateElement("Itinerary");
                newItinerary.InnerXml = strItinerary;

            return xmlDoc;


In the following example, ExceptionLog table has an xml column called TMXML. This contains a canonical xml message. The SQL can “peer” into the xml column, and pull out selected fields.

  'varchar(24)') AS RequestType,
  'varchar(24)') AS CurrentStepName,
  'varchar(24)') AS CurrentProcessCode
FROM ExceptionLog

A nifty idea is to put the above SQL in a view, and hide the xquery statements from the common user. Then the user can simply do

Select * from ViewExceptionLog

NOTE 1: The xpath must return a single value, else you will get an error something like this:

XQuery [TMXML.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'

This is why each element in the hierarchy has the [1] after it, to return only the first nonoccurence. Even if you data doesn’t have multiple of them, T-SQL doesn’t know, you have to be explicit.

NOTE 2: if you are copying your xpath from C#, it’s probably easier to replace the single quotes with double quotes, as C# and SQL use the opposite quotes delimiters by default.

NOTE 3: Use a tool like http://www.xpathtester.com/xpath to test your xpath outside of SQL. You can paste your xml text message there, and play with different xpath statements. Then when you have one that works, go back and plug it into your T-SQL query.

For further info: http://msdn.microsoft.com/en-us/library/ms178030.aspx

What if you need to remove all the empty nodes in an XML document? It’ easy with this small subroutine. This might be useful to set fields to NULL when they have no value, especially when communicating between BizTalk and a WCF web service. You might often get serialization errors when, for example, a date/time field has an empty-string value. Better to pass no element to the web service (i.e. NULL) than a field with a bad value.

        public static XmlDocument RemoveEmptyNodes(XmlDocument txd)

           // make a clean copy so we don't accidentally destroy the byRef txd variable passed to us.
            XmlDocument xmldoc = new XmlDocument();
            XmlNodeList emptyElements = xmldoc.SelectNodes(@"//*[not(node())]");
            for (int i = emptyElements.Count - 1; i >= 0; i--)
            xmldoc.InnerXml = xmldoc.InnerXml.Replace("", "");
            return xmldoc;

You can call the above code from a message assignment shape in an orchestration.
Just put the above code in a C# helper .DLL, make a reference to it from your orchestration, then you should be able to call it statically.

XML Serializer – Sample Code – How to take a C# object and write it to a file in XML “serialized” format.

NOTE: Serialize means to take an object (in memory) and turn it to a format that can be preserved to disk (or sent over a wire). Deserialize means to take the serialized-format, and turn it back into an object (in memory).

using System.Xml.Serialization;
using System.IO;

//  Serialize an object in memory to disk. 

            XmlSerializer xs1 = new XmlSerializer(typeof(YourClassName));
            StreamWriter sw1 = new StreamWriter(@"c:DeserializeYourObject.xml");
            xs1.Serialize(sw1, objYourObjectFromYourClassName);

// Now to deserialize it - assuming this might be a different program, run later.

            XmlSerializer xs2 = new XmlSerializer(typeof(YourClassName));
            StreamReader sr2 = new StreamReader(@"c:DeserializeYourObject.xml");
            // deserialize and cast back to proper class
            objYourObjectFromYourClassName = (YourClassName) xs2.Deserialize(sr2);
            Console.WriteLine ("Deserialize2 completed");


NOTE: Serializing to a string in memory is a lot trickier than you might think, because you have to deal with byteArrays, and encoding. Here’s a link to a page that explains how to do it:


Based on the above article, I put the following code in my “Common” C# Component library that is deployed on all my systems:

        /// <summary>
        /// Method to convert a custom Object to XML string
        /// </summary>
        /// Object that is to be serialized to XML
        /// XML string
        public static String SerializeObject(Object pObject)


                String XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(pObject.GetType());
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObject);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return XmlizedString;


            catch (Exception e)
                return null;

        /// <summary>
        /// Method to reconstruct turn XMLString back into Object
        /// </summary>

        public static Object DeserializeObject(String pXmlizedString, Type classType)

            XmlSerializer xs = new XmlSerializer(classType);
            MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            return xs.Deserialize(memoryStream);


        private static String UTF8ByteArrayToString(Byte[] characters)
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);

        private static Byte[] StringToUTF8ByteArray(String pXmlString)
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;


Just wrap the above with your class name, and add these using statements:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Xml.Schema;
using System.IO;
using System.Xml.Serialization;
using System.Text;