A Scala version based on Zaz's answer.
case class DocumentEx(document: Document) {
def toXmlString(pretty: Boolean = false):Try[String] = {
getStringFromDocument(document, pretty)
}
}
implicit def documentToDocumentEx(document: Document):DocumentEx = {
DocumentEx(document)
}
def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
try
{
val domSource= new DOMSource(doc)
val writer = new StringWriter()
val result = new StreamResult(writer)
val tf = TransformerFactory.newInstance()
val transformer = tf.newTransformer()
if (pretty)
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
transformer.transform(domSource, result)
Success(writer.toString);
}
catch {
case ex: TransformerException =>
Failure(ex)
}
}
With that, you can do either doc.toXmlString()
or call the getStringFromDocument(doc)
function.