Henry Henrinson
Henry Henrinson

Reputation: 5392

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

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:

Upvotes: 10

Views: 612

Answers (2)

Chris
Chris

Reputation: 2791

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.

Upvotes: 1

Henry Henrinson
Henry Henrinson

Reputation: 5392

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.

Upvotes: 1

Related Questions