XML/DOM serialization: Difference between revisions

Added Kotlin
(Lingo added)
(Added Kotlin)
Line 618:
var xmlString = xml.toXMLString();</lang>
 
=={{header|Kotlin}}==
This is the closest I could get to the required output.
 
There appears to be no satisfactory way to prevent the default encoding and standalone attributes from appearing in the XML declaration using the standard JDK DOM implementation. If you set the standalone attribute to true - using doc.setXmlStandalone(true) - then this removes it from the declaration but unfortunately there is then no carriage return before the <root> tag!
 
So I've decided to leave it as it is.
<lang scala>// version 1.1.3
 
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.dom.DOMSource
import java.io.StringWriter
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory
 
fun main(args: Array<String>) {
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
val doc = dBuilder.newDocument()
val root = doc.createElement("root") // create root node
doc.appendChild(root)
val element = doc.createElement("element") // create element node
val text = doc.createTextNode("Some text here") // create text node
element.appendChild(text)
root.appendChild(element)
 
// serialize
val source = DOMSource(doc)
val sw = StringWriter()
val result = StreamResult(sw)
val tFactory = TransformerFactory.newInstance()
tFactory.newTransformer().apply {
setOutputProperty("indent", "yes")
setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
transform(source, result)
}
println(sw)
}</lang>
 
{{out}}
<pre>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<element>Some text here</element>
</root>
</pre>
 
=={{header|Lasso}}==
9,485

edits