Skip to content

Instantly share code, notes, and snippets.

@fomkin
Created January 12, 2018 08:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fomkin/f3709afdf53dd0a9e06e07eb16b979f2 to your computer and use it in GitHub Desktop.
Save fomkin/f3709afdf53dd0a9e06e07eb16b979f2 to your computer and use it in GitHub Desktop.
Generate Levsha nodes from HTML
import scala.xml.XML
import scala.xml.{Node => XmlNode}
import levsha.Document.Node
def nodeFromHtml[T](html: String): Node[T] = Node[T] { rc =>
val document = XML.loadString(html)
def aux(node: XmlNode): Unit = node match {
case scala.xml.Text(text) =>
rc.addTextNode(text)
case _ =>
rc.openNode(XmlNs.html, node.label)
node.attributes.foreach { attr =>
rc.setAttr(XmlNs.html, attr.key, attr.value.head.text)
}
node.child.foreach { child =>
aux(child)
}
rc.closeNode(node.label)
}
aux(document.head)
}
// Usage
'body(
'div("Static html"),
nodeFromHtml("<span>Dynamic html</span>")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment