1

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.

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>)
}

The test doesnotWork results in an exception:

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

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

2
  • 1
    Unless your fragments are XHTML, you will want to parse with Html5.parse. Commented Feb 21, 2012 at 14:47
  • 1
    And by parsing your own HTML, you are avoiding Lift's XSS protections. Be sure to sanitize your HTML before sending back to the browser. Commented Feb 21, 2012 at 14:50

2 Answers 2

5

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>)
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I didn't know the Children snippet.
3

You don't need a full valid XML document, but you do need a single top-level tag.

As you observed, the following works:

XML.loadString("<fragment><p>A</p><p>B</p></fragment>")

You could then either store a sequence of Elems, or wrap them in a custom tag and extract the sequence using .descendant.

1 Comment

This also works - thank you. But I will use the simple Children-Snippet-workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.