added a little spike of a little std.dom API to make the W3C DOM API a little kooler

This commit is contained in:
James Strachan
2012-02-06 16:49:49 +00:00
parent 5057bf732e
commit a3cd65f10e
7 changed files with 173 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
package std.dom
import org.w3c.dom.*
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import std.getOrElse
// Properties
var Element.id : String
get() = this.getAttribute("id").getOrElse("")
set(value) {
this.setAttribute("id", value)
}
var Element.style : String
get() = this.getAttribute("style").getOrElse("")
set(value) {
this.setAttribute("style", value)
}
var Element.cssClass : String
get() = this.getAttribute("class").getOrElse("")
set(value) {
this.setAttribute("class", value)
}
// Syntax sugar
inline fun Node.plus(child: Node?): Node {
if (child != null) {
this.appendChild(child)
}
return this
}
+53
View File
@@ -0,0 +1,53 @@
/**
* JVM specific API implementations using JAXB and so forth which would not be used when compiling to JS
*/
package std.dom
import org.w3c.dom.*
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import javax.xml.transform.Source
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import java.io.StringWriter
import javax.xml.transform.OutputKeys
fun createDocument(builder: DocumentBuilder): Document {
return builder.newDocument().sure()
}
fun createDocument(builderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance().sure()): Document {
return createDocument(builderFactory.newDocumentBuilder().sure())
}
fun createTransformer(source: Source? = null, factory: TransformerFactory = TransformerFactory.newInstance().sure()): Transformer {
val transformer = if (source != null) {
factory.newTransformer(source)
} else {
factory.newTransformer()
}
return transformer.sure()
}
fun Node.toXmlString(xmlDeclaration: Boolean = this is Document): String {
return nodeToXmlString(this, xmlDeclaration)
}
/*
fun Document.toXmlString(xmlDeclaration: Boolean = true): String {
return nodeToXmlString(this, xmlDeclaration)
}
*/
fun nodeToXmlString(node: Node, xmlDeclaration: Boolean): String {
val transformer = createTransformer()
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, if (xmlDeclaration) "no" else "yes")
val buffer = StringWriter()
transformer.transform(DOMSource(node), StreamResult(buffer))
return buffer.toString().sure()
}