scala.xml.XML.loadString v. scala.xml.Source#fromString

587 views
Skip to first unread message

Kevin Meredith

unread,
Apr 16, 2015, 11:13:44 PM4/16/15
to scala...@googlegroups.com
I'm not sure when to use one method versus the other.

XML#loadString

scala> val xml = """<script type="text/javascript">
     |      |      foo("{bar}");
     |      | </script>"""
xml: String =
<script type="text/javascript">
     |      foo("{bar}");
     | </script>

scala> scala.xml.XML.loadString(xml)
res0: scala.xml.Elem =
<script type="text/javascript">
     |      foo(&quot;{bar}&quot;);
     | </script>

Source#fromString

scala> scala.xml.Source.fromString(xml)
res1: org.xml.sax.InputSource = org.xml.sax.InputSource@4a183d02

I tried to print out `InputSource` by getting an InputStream, and then using this answer - http://stackoverflow.com/a/309448/409976.

However, I got null when doing:

scala> res1.getByteStream
res2: java.io.InputStream = null

So, I have 2 questions: 
  1. when to use Source#fromString versus XML#loadString
  2. how to print out/use the InputSource from Source#fromString
Thanks.

Daniel Manchester

unread,
Apr 17, 2015, 3:14:09 PM4/17/15
to scala...@googlegroups.com
Hi,

I'd probably only use Source#fromString if I were doing SAX parsing. By design, it does not XML-parse the String you give it. Parsing only occurs when you pass the returned InputSource to a parser. Consequently, Source#fromString returns an InputSource even if you give it ill-formed XML:

scala> scala.xml.Source.fromString("foo")
res0: org.xml.sax.InputSource = org.xml.sax.InputSource@114e8ac

XML#loadString, on the other hand, actually parses its input and raises an error on ill-formed XML:

scala> scala.xml.XML.loadString("foo")
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
        ...

Dan

Som Snytt

unread,
Apr 17, 2015, 6:45:55 PM4/17/15
to scala-user
The definition in XMLLoader[T <: Node], where object XML extends XMLLoader[Elem]:

def loadString(string: String): T = loadXML(fromString(string), parser)

Use XML.withSAXParser(p) to procure an XMLLoader that uses a particular parser.



--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages