Skip to content

Instantly share code, notes, and snippets.

@kaja47
Created August 27, 2018 03:19
Show Gist options
  • Save kaja47/35b182d358117243e6199d66c9fd4df2 to your computer and use it in GitHub Desktop.
Save kaja47/35b182d358117243e6199d66c9fd4df2 to your computer and use it in GitHub Desktop.
nicer javax.xml.stream.XMLStreamWriter
object XMLSW {
private val f = XMLOutputFactory.newInstance
def document(encoding: String = "utf-8", version: String = "1.0")(body: XMLSW => Unit) = {
val out = new StringWriter()
val w = f.createXMLStreamWriter(out)
val ww = new XMLSW(w)
ww.document(encoding, version)(body)
w.flush()
w.close()
out.toString
}
}
class XMLSW(val w: XMLStreamWriter) {
def document(encoding: String, version: String)(body: XMLSW => Unit) = {
w.writeStartDocument(encoding, version)
body(this)
w.writeEndDocument()
}
def element(localName: String, content: String) = {
w.writeStartElement(localName)
w.writeCharacters(content)
w.writeEndElement()
}
def element(localName: String, attributes: XMLSW => Unit, content: String) = {
w.writeStartElement(localName)
attributes(this)
w.writeCharacters(content)
w.writeEndElement()
}
def element(localName: String)(body: XMLSW => Unit) = {
w.writeStartElement(localName)
body(this)
w.writeEndElement()
}
def attribute(localName: String, value: String) =
w.writeAttribute(localName, value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment