hertzsprung
hertzsprung

Reputation: 9893

Using Jackson XmlMapper to serialize to an XML DOM

I know it's possible to serialize directly to a String using XmlMapper.writeValueAsString(), but I would like to serialize a DOM tree. Either a new Document or, preferably, serialize directly to an existing DOM Node. Can this be done with Jackson?

Upvotes: 8

Views: 1821

Answers (1)

Rick Riemer
Rick Riemer

Reputation: 84

I think I found the solution by using an XMLStreamWriter.

Try the following snippet:

XMLOutputFactory factory = XMLOutputFactory.newInstance();
factory.createXMLStreamWriter(new DOMResult(yourNode));

XmlMapper mapper = new XmlMapper();
ToXmlGenerator xmlGenerator = mapper .getFactory().createGenerator(sw);
mapper.writerFor(YourClass.class).writeValue(xmlGenerator, yourInstance);

Upvotes: 2

Related Questions