Reputation: 13406
If using the vanilla XML DOM, I can serialize a Document
object to a String
in Java like this:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
String result = stringWriter.getBuffer().toString();
If I'm using the S9 API that's part of Saxon 9.7 HE, and I have DocumentInfo
object, how can I serialize it to a String
?
Edit: Here's a complete working example, which is based upon @Michael Kay's answer:
Processor processor = new Processor(false); // False = does not required a feature from a licensed version of Saxon.
Serializer serializer = processor.newSerializer();
// Other properties found here: http://www.saxonica.com/html/documentation/javadoc/net/sf/saxon/s9api/Serializer.Property.html
serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "no");
serializer.setOutputProperty(Serializer.Property.INDENT, "yes");
XdmNode xdmNode = new XdmNode(documentInfo);
String result = serializer.serializeNodeToString(xdmNode);
Upvotes: 3
Views: 1222
Reputation: 163488
Well, firstly, the DocumentInfo isn't actually part of the s9api API: in s9api, a node is represented by an XdmNode object.
One way you can serialize a DocumentInfo is using exactly the code you have shown us: NodeInfo extends Source, so you can use it as the first argument of transform().
But in s9api the simplest approach is:
Processor proc = new Processor();
Serializer ser = proc.newSerializer();
ser.setOutputProperty(....);
ser.serializeNode(node);
In that code, "node" is an XdmNode; if you want to use a DocumentInfo, then you can call the constructor
new XdmNode(documentInfo);
Upvotes: 4