Scala:解析HTML片段 [英] Scala: Parse HTML-fragment

查看:317
本文介绍了Scala:解析HTML片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的数据库存储f.ex之类的HTML 片段. <p>A.</p><p>B.</p>.我想将数据库中的HTML片段添加到Lift片段中.

Our database stores HTML fragments like f.ex. <p>A.</p><p>B.</p>. I want to include the Html fragements from the database into a Lift snippet.

为此,我尝试使用XML.loadString()方法将片段转换为scala.xml.Elem,但这仅适用于 full 有效的XML文档:

To do that, I tried to use the XML.loadString()-method to convert the fragement into a scala.xml.Elem, but this only works for full valid XML-documents:

import scala.xml.XML
@Test
def doesnotWork() {
  val result = XML.loadString("<p>A</p><p>B</p>")
  assert(result === <p>A</p><p>B</p>)
}

@Test
def thisWorks() {
  val result = XML.loadString("<test><p>A</p><p>B</p></test>")
  assert(result === <test><p>A</p><p>B</p></test>)
}

测试doesnotWork导致异常:

org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 10; The markup in the document following the root element must be well-formed.

是否可以将仅(有效)片段转换为XML?

Is it possible to convert just (valid) fragements to XML?

推荐答案

由于使用的是Lift,因此可以将XML包装在 Children 代码段简单地返回元素的子元素;对于包装您需要解析的片段非常有用.

Since you're using Lift, you can wrap your XML in lift:children as a workaround. The Children snippet simply returns the element's children; and is very useful for wrapping fragments you need to parse.

@Test
def thisAlsoWorks() {
  val result = XML.loadString("<lift:children><p>A</p><p>B</p></lift:children>")
  assert(result === <lift:children><p>A</p><p>B</p></lift:children>)
 }

这篇关于Scala:解析HTML片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆