Created
December 15, 2016 19:59
-
-
Save dmcg/6a672a621d712f6ebcabe202fed40991 to your computer and use it in GitHub Desktop.
Kotlin XML builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun article(licenceCode: String) = elem("article") { | |
elem("front") { | |
elem("journal-meta") { | |
elem("journal-id", "journal-id-type" to "publisher") { | |
text(licenceCode) | |
} | |
} | |
} | |
elem("body") | |
} | |
// Generates | |
<article> | |
<front> | |
<journal-meta> | |
<journal-id journal-id-type="publisher">licence</journal-id> | |
</journal-meta> | |
</front> | |
<body /> | |
</article> | |
import org.jdom2.Attribute | |
import org.jdom2.Element | |
import org.jdom2.Text | |
fun elem(name: String, vararg attributes: Pair<String, String>, init: Element.() -> Unit = {}) = | |
createElement(name, *attributes, init = init) | |
fun Element.elem(name: String, vararg attributes: Pair<String, String>, init: Element.() -> Unit = {}): Element = | |
addContent(createElement(name, *attributes, init = init)) | |
fun Element.text(value: String): Element = addContent(Text(value)) | |
private fun createElement(name: String, vararg attributes: Pair<String, String>, init: Element.() -> Unit = {}) = Element(name).apply { | |
attributes.forEach { this.attributes.add(Attribute(it.first, it.second)) } | |
this.init() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment