Search code examples
c#xmlmsmq

Send XML message to MSMQ without any formatting


I need to send an XMLDocument object to MSMQ. I don’t have a class to deserialize it into (the xml may vary). The default formatter, XMLMessageFormatter, will “pretty print” the object. This causes a problem since

<text></text>

Will be converted to

<text>

</text>

(I.e. cr + spaces). The message is being read by a process using the default XMLMessageFormatter and hasn’t been an issue whilst nodes have data in them. This is an issue, however, further down the line, as a process (out of my control) will interpret these new characters as data and cause an error.

I know I could write some code to convert them using IsEmpty = true giving <text /> but I’d like a solution that doesn’t alter the object at all.

BinaryMessageFormatter will prefix the data with BOM data (receiver is not expecting that) and ActiveXMessageFormatter will double byte the string (again causing issues the other end).

I would rather like to avoid having to write a custom message formatter. I’ve tried including some options in the XMLMessageFormatter but they’ve had little effect. Any ideas would be very much appreciated.


Solution

  • MSMQ operates on raw blobs. You do not have to use a formatter unless you want to.

    To send a message and get it back byte-for-byte identical, use the BodyStream property.

    Example:

    var queue = new MessageQueue(@".\private$\queueName");
    var msg = new Message();
    msg.BodyStream = new MemoryStream(Encoding.UTF8.GetBytes("<root><test></test></root>"));
    queue.Send(msg);
    

    Resultant message:

    Screenshot showing unmolested XML