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

我可以使用Scala的内置xml处理程序忽略无效的XML字符吗?

发布时间:2020-12-16 18:25:46 所属栏目:安全 来源:网络整理
导读:我有一个xml文件(来自联邦政府的data.gov),我试图用 scala的xml处理程序阅读. val loadnode = scala.xml.XML.loadFile(filename) 显然,有一个无效的xml字符.是否可以选择忽略无效字符?或者是我唯一可以先清理它的选择? org.xml.sax.SAXParseException: An
我有一个xml文件(来自联邦政府的data.gov),我试图用 scala的xml处理程序阅读.

val loadnode = scala.xml.XML.loadFile(filename)

显然,有一个无效的xml字符.是否可以选择忽略无效字符?或者是我唯一可以先清理它的选择?

org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x12) was found in the element content of the document.

Ruby的nokogiri能够用无效字符解析它.

解决方法

我确实想知道即使在XML 1.1中0x12是否有效.在1.0和1.1的差异上看到这个 summary.特别是:

In addition,XML 1.1 allows you to
have control characters in your
documents through the use of character
references. This concerns the control
characters #x1 through #x1F,most of
which are forbidden in XML 1.0. This
means that your document can now
include the bell character,like this:
. However,you still cannot have
these characters appear directly in
your documents; this violates the
definition of the mime type used for
XML (text/xml).

Xerces可以解析XML 1.1,但似乎期望实体而不是真正的0x12字符:

val s = "<?xml version='1.1'?><root>u0012</root>"
// causes An invalid XML character (Unicode: 0x12)
//XML.loadXML(xml.Source.fromString(s),XML.parser)

val u = "<?xml version='1.1'?><root>&#18;</root>"
val v = XML.loadXML(xml.Source.fromString(u),XML.parser)
println(v) // works

正如lavinio所建议的,您可以过滤掉无效字符.这在Scala中不占用太多行:

val in = new InputStream {
  val in0 = new FileInputStream("invalid.xml")
  override def read():Int = in0.read match { case 0x12=> read() case x=> x}
}
val x = XML.load(in)

(编辑:李大同)

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

    推荐文章
      热点阅读