我们的数据库存储像f.ex这样的HTML 片段.<p>A.</p><p>B.</p>.我想将数据库中的Html fragements包含在Lift片段中.
为此,我尝试使用XML.loadString()-method将fragement转换为a scala.xml.Elem,但这仅适用于完整有效的XML文档:
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>)
}
Run Code Online (Sandbox Code Playgroud)
测试doesnotWork结果例外:
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 10; The markup in the document following the root element must be well-formed.
Run Code Online (Sandbox Code Playgroud)
是否可以将(有效的)fragements转换为XML?
由于您使用的是Lift,因此可以将XML包装lift:children为变通方法.该Children片段只返回元素的儿童; 并且对于包装需要解析的片段非常有用.
@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>)
}
Run Code Online (Sandbox Code Playgroud)