【发布时间】:2012-08-18 07:21:29
【问题描述】:
任务:HTML - Scala 中的解析器。我对 scala 很陌生。
到目前为止:我已经用 Scala 编写了一个小 Parser 来解析随机的 html 文档。
import scala.xml.Elem
import scala.xml.Node
import scala.collection.mutable.Queue
import scala.xml.Text
import scala.xml.PrettyPrinter
object Reader {
def loadXML = {
val parserFactory = new org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl
val parser = parserFactory.newSAXParser()
val source = new org.xml.sax.InputSource("http://www.randomurl.com")
val adapter = new scala.xml.parsing.NoBindingFactoryAdapter
val feed = adapter.loadXML(source, parser)
feed
}
def proc(node: Node): String =
node match {
case <body>{ txt }</body> => "Partial content: " + txt
case _ => "grmpf"
}
def main(args: Array[String]): Unit = {
val content = Reader.loadXML
Console.println(content)
Console.println(proc(content))
}
}
问题是“proc”不起作用。基本上,我想准确获取一个节点的内容。或者有没有其他方法可以在不匹配的情况下实现?
loadxml 函数中的“提要”是否为我提供了正确的解析格式,或者有更好的方法来实现吗? Feed 还给我根节点,对吧?
提前致谢
【问题讨论】:
-
将 HTML 解析为 XML 绝不是一个好主意。为此目的,有一些不错的 Java 库。 Jsoup 就是其中之一。
-
@NikitaVolkov:这就是提问者使用 TagSoup 解析器的原因,它为非 XML HTML 提供了一个很好的 SAX 接口。
-
@TravisBrown 哦,好的。没注意到
标签: html xml scala xml-parsing html-parsing