Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 427
hertzsprung Avatar asked Jun 20 '13 15:06

hertzsprung


People also ask

Can Jackson parse XML?

Jackson is a library for handling JSON in Java systems and now has support for XML from version 2. DOM4J is a memory-efficient library for parsing XML, XPath, and XSLT (eXtensible Stylesheet Language). JDom which is an XML parsing library with support for XPath and XSLT.

Can ObjectMapper be used for XML?

We can also read XML, using the various readValue APIs that are part of provided by the ObjectMapper. For example, reading some XML from an InputStream into a Java Bean: MyBean bean = objectMapper.

What is Jackson Dataformat XML?

Data format extension for Jackson (http://jackson.codehaus.org) to offer alternative support for serializing POJOs as XML and deserializing XML as pojos. Support implemented on top of Stax API (javax. xml.

What is serialization in XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.


1 Answers

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);
like image 166
Rick Riemer Avatar answered Sep 28 '22 12:09

Rick Riemer