【问题标题】:How can I convert scala.xml.Elem to something compatible with the javax.xml APIs?如何将 scala.xml.Elem 转换为与 javax.xml API 兼容的东西?
【发布时间】:2009-11-23 16:07:37
【问题描述】:

我有一些 XML 的 Scala 表示(即 scala.xml.Elem),我想将它与一些标准 Java XML API(特别是 SchemaFactory)一起使用。看起来我需要将我的Elem 转换为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)))

【问题讨论】:

    标签: java xml scala interop


    【解决方案1】:

    你想要的是可能 - 你只需要通过声明一个隐式方法轻轻地告诉 Scala 编译器如何从scala.xml.Elem 转到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)
    

    它并没有更高效,但是一旦你把隐式方法定义排除在外,它肯定会更漂亮。

    【讨论】:

    • 感谢您的回复。虽然这样看起来肯定更好,但它仍在将 Elem 写入字符串并重新读取,这是我希望避免的。
    • 由于替代方案并没有完全涌入,我将接受这个答案(我在我的应用程序中也坚持使用这种方法)。谢谢。
    • 没问题。我希望我知道一个更好的答案,但我对 Java 不太熟悉。由于 Scala,我重新回到了 Java 生态系统。至少这样你的代码会更简洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    相关资源
    最近更新 更多