代码之家  ›  专栏  ›  技术社区  ›  overthink

如何将scala.xml.Elem转换为与javax.xml API兼容的东西?

  •  6
  • overthink  · 技术社区  · 16 年前

    scala.xml.Elem ),我想将它与一些标准的JavaXMLAPI(特别是 SchemaFactory ). 看起来像是把我的 Elem javax.xml.transform.Source 这是我需要做的,但我不确定。我可以找到各种方法来有效地写出我的 并将其读入与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)))
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   Steven Merrill    16 年前

    你想要的是 -您只需轻轻地告诉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)
    

    它的效率并没有提高,但一旦你得到了隐式方法定义,它肯定会更漂亮。

    推荐文章