返回顶部

收藏

将 Scala XML 转成 Java DOM

更多

[Scala]代码

object XmlHelpers {
    val docBuilder =
    javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder()
}

class NodeExtras(n: Node) {
    def toJdkNode(doc: org.w3c.dom.Document): org.w3c.dom.Node =
    n match {
    case Elem(prefix, label, attributes, scope, children @ _*) =>
    // XXX: ns
    val r = doc.createElement(label)
    for (a <- attributes) {
    r.setAttribute(a.key, a.value.text)
    }
    for (c <- children) {
    r.appendChild(c.toJdkNode(doc))
    }
    r
    case Text(text) => doc.createTextNode(text)
    case Comment(comment) => doc.createComment(comment)
    // not sure
    case a: Atom[_] => doc.createTextNode(a.data.toString)
    // XXX: other types
    //case x => throw new Exception(x.getClass.getName)
    }
    }

    class ElemExtras(e: Elem) extends NodeExtras(e) {
    override def toJdkNode(doc: org.w3c.dom.Document) =
    super.toJdkNode(doc).asInstanceOf[org.w3c.dom.Element]

    def toJdkDoc = {
    val doc = XmlHelpers.docBuilder.newDocument()
    doc.appendChild(toJdkNode(doc))
    doc
    }
}

implicit def nodeExtras(n: Node) = new NodeExtras(n)
implicit def elemExtras(e: Elem) = new ElemExtras(e)

标签:Scala,jQuery,XML,DOM

收藏

0人收藏

支持

0

反对

0

发表评论