Usage
endpointConfiguration.UseSerialization<XmlSerializer>();
Inferring message type from root node name
In integration scenarios where the sender is unable to add headers to the message, the serializer can infer the CLR message type based on the root node of the XML payload. To take advantage of this, the name of the payload's root node must match the Type.
of a message type known to the receiving endpoint.
This technique allows messages without any headers, including the NServiceBus.
header, to be processed. This is demonstrated by the native integration with RabbitMQ sample.
Raw XML
In certain integration scenarios it may be necessary to bypass NServiceBus's opinionated serialization format (essentially key/value pairs) and directly send custom XML structures over messaging. In order to do that, declare one or more properties on the message contract as XDocument
or XElement
.
Message with XDocument
public class MessageWithXDocument :
IMessage
{
// name and casing must match the rootnode
public XDocument nutrition { get; set; }
}
Payload with XDocument
<nutrition>
<daily-values>
<total-fat units='g'>65</total-fat>
<saturated-fat units='g'>20</saturated-fat>
</daily-values>
</nutrition>
Message with XElement
public class MessageWithXElement :
IMessage
{
// name and casing must match the rootnode
public XElement nutrition { get; set; }
}
Payload with XElement
<nutrition>
<daily-values>
<total-fat units='g'>65</total-fat>
<saturated-fat units='g'>20</saturated-fat>
</daily-values>
</nutrition>
The caveat of this approach is that the serializer will wrap the data in an outer node named after the name of the property. In the examples above, note the associated expected payloads.
To avoid that, for interoperability reasons, instruct the serializer not to wrap raw XML structures:
var serialization = endpointConfiguration.UseSerialization<XmlSerializer>();
serialization.DontWrapRawXml();
Caveats
XML attributes
The XML serializer in NServiceBus is a custom implementation. As such it does not support the standard .NET XML attributes.