如何将scala.xml.Elem转换为与javax.xml API兼容的东西?
我有一些XML(即a)的Scala表示,我想将其与一些标准JavaXMLAPI(特别是)一起使用。看起来我需要将如何将scala.xml.Elem转换为与javax.xml API兼容的东西?,java,xml,scala,interop,Java,Xml,Scala,Interop,我有一些XML(即a)的Scala表示,我想将其与一些标准JavaXMLAPI(特别是)一起使用。看起来我需要将元素转换为a,但我不确定。我可以找到各种方法来有效地写出我的Elem,并将其读入与Java兼容的内容,但我想知道是否有一种更优雅(希望更有效)的方法 Scala代码: import java.io.StringReader import javax.xml.transform.stream.StreamSource import javax.xml.validation.{Schema
元素
转换为a,但我不确定。我可以找到各种方法来有效地写出我的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)))
导入java.io.StringReader
导入javax.xml.transform.stream.StreamSource
导入javax.xml.validation.{Schema,SchemaFactory}
导入javax.xml.xmlstants
val schemaXml=
val schemaFactory=schemaFactory.newInstance(xmlstants.W3C_XML_SCHEMA_NS_URI);
//不可能,但我想要的是:
//val schema=schemaFactory.newSchema(schemaXml)
//我现在正在做什么(丑)
val schema=schemaFactory.newSchema(新的StreamSource(新的StringReader(schemaXml.toString)))
您想要的是可能的-您只需通过声明隐式方法温和地告诉Scala编译器如何从Scala.xml.Elem
到javax.xml.transform.stream.StreamSource
导入java.io.StringReader
导入javax.xml.transform.stream.StreamSource
导入javax.xml.validation.{Schema,SchemaFactory}
导入javax.xml.xmlstants
导入scala.xml.Elem
val schemaXml=
val schemaFactory=schemaFactory.newInstance(xmlstants.W3C_XML_SCHEMA_NS_URI);
隐式def-toStreamSource(x:Elem)=新流源(新StringReader(x.toString))
//很有可能,可能还是不行:
val schema=schemaFactory.newSchema(schemaXml)
它的效率并没有提高,但一旦您将隐式方法定义排除在外,它肯定会更漂亮。感谢您的回复。虽然这种方式看起来确实更好,但它仍然将元素写入字符串并重新读取,这是我希望避免的。因为替代方法并不是如洪水般涌入,所以我将接受这个答案(我在应用程序中也坚持使用这种方法)。谢谢,没问题。我希望知道更好的答案,但我对Java不太熟悉。因为Scala,我跳回Java生态系统。至少这样你的代码会更简洁。
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)