How to send and receive XML messages with DOM or JAXB
It is very common to send XML in JMS messages. Unfortunately, JMS does not support this directly. The best way to do create XML messages is to write the XML document into a BytesMessage or StreamMessage. Another common practice is to put the XML into a TextMessage, but this can be tricky to get right (more).
Sending and Receiving XML with DOM
Session session = ...;
// Write DOM document into message
Document doc = ...; // input document
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(baos));
BytesMessage msg = session.createBytesMessage();
msg.writeBytes(baos.toByteArray());
// Read DOM document from message
byte[] content = new byte[(int) msg.getBodyLength()];
msg.readBytes(content);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document msgDoc = builder.parse(new ByteArrayInputStream(content)); // result
Sending and Receiving XML with JAXB
Session session = ...;
JAXBContext ctx = ...;
// Write JAXB document into message
Object doc = ...; // input document
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Marshaller marshaller = ctx.createMarshaller();
marshaller.marshal(doc, baos);
BytesMessage msg = session.createBytesMessage();
msg.writeBytes(baos.toByteArray());
// Read JAXB document from message
byte[] content = new byte[(int) msg.getBodyLength()];
msg.readBytes(content);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
Object msgDoc = unmarshaller.unmarshal(new ByteArrayInputStream(content)); // result