Java DOMSerializer-class And Method Code Example

Here is an example of how to use the DOMSerializer class in the com.fasterxml.jackson.databind package to serialize a Java object into a W3C DOM Document:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.w3c.dom.Document;

public class Example {
    public static void main(String[] args) throws Exception {
        Person person = new Person("John Doe", 30);

        ObjectMapper mapper = new XmlMapper();
        Document doc = mapper.writeValueAsDocument(person);

        // Use the DOM Document as needed, for example, to print the XML

class Person {
    private String name;
    private int age;

    public Person(String name, int age) { = name;
        this.age = age;

    // getters and setters

In this example, the XmlMapper class is used to create an instance of the mapper, and the writeValueAsDocument() method is used to serialize the Person object into a Document object.

Note that the writeValueAsDocument() method is a convenience method that wraps the writeValue() method and returns the result as a Document object.

Also, you can use the writeValue() method that accepts a Result parameter, and you can use a DOMResult object to store the result in a Document object:

   DOMResult result = new DOMResult();
   mapper.writeValue(result, person);
   Document doc = (Document)result.getNode();

It's important to notice that this is a basic example and the output format might not be exactly the way you want it. You may need to configure the mapper according to your specific needs.