Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a quick way to convert Java xml objects to Scala xml objects?

Tags:

java

xml

scala

api

Scala has its own XML library and it offers built-in support for it. However, one of the main features of the language is the touted as Java compatibility. I would expect to be able to use java Node objects in a similar way as I use scala ones.

My questions are:

  • What's the quickest way to convert java xml containers to scala ones?
  • Are there any nice implicits that do stuff for you?
  • Is there a constructor that takes a java Element, say, in the Scala API?
like image 892
Henry Henrinson Avatar asked Sep 05 '11 14:09

Henry Henrinson


2 Answers

So, I've dug around and this is the best I could find: http://www.jdom.org/docs/apidocs/org/jdom/output/XMLOutputter.html

The easiest way to use this would be in an implicit:

implicit def javaToScalaXML(jElem: org.jdom.Element): scala.xml.Element = {
    return XML.loadstring(XMLOuputter.outputString(jElem))
}

This isn't very pretty for really large xml objects as they get converted to String and then back to an XML object, but it works for small and medium sized ones.

like image 98
Henry Henrinson Avatar answered Nov 08 '22 15:11

Henry Henrinson


Whilst not exactly for Scala XML, there is a solution for Scales Xml.

It provides full TrAX support and, under the normal 'Sun' JAXP impl (not all other providers allow this), allows conversions using StAX. That means you can convert between Scales Xml and JAXP (or any other model that supports TrAX) without serializing to a string first.

There is however a lot of existing infrastructure out there for straight DOM objects that's not really directly supportable given the immutability of all three Scala Xml alternatives.

like image 39
Chris Avatar answered Nov 08 '22 15:11

Chris