0

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.

1 Answers1

2

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

Mitch
  • 21,223
  • 6
  • 63
  • 86
  • Unfortunately, not specifying a formatter applies XmlMessageFormat by default, despite what the documentation suggests even when using BodyStream. So `` results in `.. .. ..` (CR and spaces inserted) – Stephen Maitland Dec 12 '20 at 01:40
  • @StephenMaitland, I cannot reproduce that behavior. I added example code to the answer - `Body` and `Formatter` are ignored if you use `BodyStream`. – Mitch Dec 12 '20 at 07:07
  • Ah that's it thanks, I was not using a byte array. Marked as accepted. – Stephen Maitland Dec 14 '20 at 01:43