ove*_*ink 6 java xml interop scala
我有一些XML(即a scala.xml.Elem)的Scala表示,我想将它与一些标准的Java XML API(特别是SchemaFactory)一起使用.看起来将我转换Elem为a javax.xml.transform.Source是我需要做的,但我不确定.我可以看到各种方法来有效地写出我的Elem并将其读入与Java兼容的东西,但我想知道是否有更优雅(并且希望更有效)的方法?
Scala代码:
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)))
Run Code Online (Sandbox Code Playgroud)
你想要的都是可能的——你只需通过声明一个隐式方法scala.xml.Elem轻轻地告诉 Scala 编译器如何从到。javax.xml.transform.stream.StreamSource
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)
Run Code Online (Sandbox Code Playgroud)
它并没有变得更高效,但一旦你摆脱了隐式方法定义,它肯定会更漂亮。
| 归档时间: |
|
| 查看次数: |
1439 次 |
| 最近记录: |