Search code examples
javasaxons9api

What is idiomatic way to serialize DOM document with S9API serializer


Using Saxon S9API, what is the idiomatic way to serialize a DOM document to output stream? Something like

Serializer result = processor.newSerializer(out);
XdmNode source = processor.newDocumentBuilder().build(new DOMSource(doc));
result.serializeNode(source);

works but is there more correct way in S9API?


Solution

  • You don't want to do DocumentBuilder.build() because that will copy the whole DOM to a tree using the default tree model (normally a TinyTree). Instead you can use DocumentBuilder.wrap() (supplying the DOM Document node) which simply creates an XdmNode as a wrapper around the DOM node.

    So:

    Serializer result = processor.newSerializer(out);
    XdmNode source = processor.newDocumentBuilder().wrap(doc);
    result.serializeNode(source);