How to convert scala.xml.Elem to something compatible with javax.xml API?

I have a Scala representation of some XML (i.e. scala.xml.Elem ) and I would like to use it with some standard Java XML APIs (in particular SchemaFactory ). It seems like converting my Elem to javax.xml.transform.Source is what I need to do, but I'm not sure. I can see various ways to efficiently write my Elem and read it into something compatible with Java, but I wonder if there is a more elegant (and, hopefully, more efficient) approach?

Scala code:

 import java.io.StringReader import javax.xml.transform.stream.StreamSource import javax.xml.validation.{Schema, SchemaFactory} import javax.xml.XMLConstants val schemaXml = <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="foo"/> </xsd:schema> val schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // not possible, but what I want: // val schema = schemaFactory.newSchema(schemaXml) // what I'm actually doing at present (ugly) val schema = schemaFactory.newSchema(new StreamSource(new StringReader(schemaXml.toString))) 
+6
java xml scala interop
source share
1 answer

What you want, maybe you just need to gently tell the Scala compiler how to go from scala.xml.Elem to javax.xml.transform.stream.StreamSource , declaring an implicit method.

 import java.io.StringReader import javax.xml.transform.stream.StreamSource import javax.xml.validation.{Schema, SchemaFactory} import javax.xml.XMLConstants import scala.xml.Elem val schemaXml = <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="foo"/> </xsd:schema> val schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); implicit def toStreamSource(x:Elem) = new StreamSource(new StringReader(x.toString)) // Very possible, possibly still not any good: val schema = schemaFactory.newSchema(schemaXml) 

It is not more efficient, but it is sure that it is more beautiful when you receive an implicit definition of a method aside.

+2
source share

All Articles