Skip to content

Commit

Permalink
Fix JVM DOM unsafe to support XML with no root element
Browse files Browse the repository at this point in the history
Fixes #83
  • Loading branch information
Sergey Mashkov committed May 4, 2018
1 parent 833a1a5 commit 3517e75
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
15 changes: 11 additions & 4 deletions jvm/src/main/kotlin/dom-jvm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import javax.xml.transform.stream.*
class HTMLDOMBuilder(val document : Document) : TagConsumer<Element> {
private val path = arrayListOf<Element>()
private var lastLeaved : Element? = null
private val documentBuilder by lazy { DocumentBuilderFactory.newInstance().newDocumentBuilder() }
private val documentBuilder: DocumentBuilder by lazy { DocumentBuilderFactory.newInstance().newDocumentBuilder() }

override fun onTagStart(tag: Tag) {
val element = when {
Expand Down Expand Up @@ -84,13 +84,20 @@ class HTMLDOMBuilder(val document : Document) : TagConsumer<Element> {
UnsafeImpl.block()
}

val UnsafeImpl = object : Unsafe {
private val UnsafeImpl = object : Unsafe {
override operator fun String.unaryPlus() {
val element = documentBuilder
.parse(InputSource(StringReader(this)))
.parse(InputSource(StringReader("<unsafeRoot>" + this + "</unsafeRoot>")))
.documentElement

val importNode = document.importNode(element, true)
path.last().appendChild(importNode)

check(importNode.nodeName == "unsafeRoot") { "the document factory hasn't created an unsafeRoot node"}

val last = path.last()
while (importNode.hasChildNodes()) {
last.appendChild(importNode.removeChild(importNode.firstChild))
}
}
}

Expand Down
19 changes: 19 additions & 0 deletions jvm/src/test/kotlin/dom-trees.kt
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,23 @@ class TestDOMTrees {
}
}
}

@test fun `script content`() {
val document = document {
append.html {
head {
script(ScriptType.textJavaScript) {
unsafe {
raw("fun f() { return 1; }")
}
}
}
}
}


assertEquals("<!DOCTYPE html>\n" +
"<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><script type=\"text/javascript\">fun f() { return 1; }</script></head></html>",
document.serialize(false).trim().replace("\r\n", "\n"))
}
}

0 comments on commit 3517e75

Please sign in to comment.