Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a NodeSeq from a string?

Tags:

xml

scala

Scala code:

val str = "<a>11</a><b>22</b>"
XML.loadString(str)

It will report an exception(of course):

org.xml.sax.SAXParseException:
The markup in the document following the root element must be well-formed.

Is it possible to load a NodeSeq from the string?

like image 898
Freewind Avatar asked Jan 24 '26 01:01

Freewind


2 Answers

The parser in scala doesn't like your example string

val str2="<xml><a>11</a><b>22</b></xml>"

works just fine, I guess that your example doesn't count as a complete document

To get the elements "inside" the <xml>..</xml> do this

val n = xml.XML.loadString(str2)
val list = n.child

which returns a List

scala> n.child
res12: Seq[scala.xml.Node] = List(<a>11</a>, <b>22</b>)
like image 173
Vorsprung Avatar answered Jan 25 '26 18:01

Vorsprung


To supplement Vorsprung's answer, the actual reason why XML.loadString fails on the input <a>11</a><b>22</b> is just what the exception tells you (emphasis mine):

The markup in the document following the root element must be well-formed.

One of the requirements of a well-formed XML document is that it contains exactly one root element.

Thus, for example this works fine and gives you a NodeSeq (an Elem to be more exact):

XML.loadString("<c><a>11</a><b>22</b></c>")
like image 28
Jonik Avatar answered Jan 25 '26 17:01

Jonik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!