加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:47:54 所属栏目:安全 来源:网络整理
导读:我有一些 XML的 Scala表示(即 scala.xml.Elem ),我想将它与一些标准的Java XML API(特别是 SchemaFactory)一起使用.看起来好像将我的Elem转换为 javax.xml.transform.Source 是我需要做的,但我不确定.我可以看到各种方法来有效地写出我的Elem并将其读入与Jav
我有一些 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)))

解决方法

您想要的是什么 – 您只需要通过声明一个隐式方法,轻轻告诉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)

它没有任何效率,但是一旦你将隐式方法定义排除在外,它肯定会更漂亮.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读