ruby-on-rails - 如何验证大 XML

标签 ruby-on-rails ruby xml validation nokogiri

我正在尝试使用 Nokogiri 针对 XSD 验证 XML 文件。 当文件很小时,我使用文档方法验证:

xsd = Nokogiri::XML::Schema(File.read(Rails.root.join('files/xsd', self::XSD)))
xml = Nokogiri::XML(File.read(Rails.root.join('public/uploads', file_path)))
xsd.validate(xml).each do |error|
end

当文件很大时,前面的方法不好用,因为需要很多资源,所以需要文件方法验证:

xsd = Nokogiri::XML::Schema(File.read(Rails.root.join('files/xsd', self::XSD)))
xml = Rails.root.join('public/uploads', file_path).to_s
xsd.validate(xml).each do |error|
end

但是第二种方式并没有向我显示简单的错误,例如属性中未闭合的双引号:

<?xml version="1.0"?>
<catalog version="123 xmlns="http://google.com">
   <book id="bk101">

第一个确实如此。

最佳答案

Nokogiri 是适用于中小型 XML 的出色工具,但是当您处理大型到超大型/巨大的文件时,您需要切换到其他工具,例如 SAX 解析,或者为了验证,类似 xmllint 的工具。 .

The xmllint program parses one or more XML files, specified on the command line as xmlfile. It prints various types of output, depending upon the options selected. It is useful for detecting errors both in XML code and in the XML parser itself.

It is included in libxml2.

关于ruby-on-rails - 如何验证大 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32568919/

相关文章:

ruby - 如何在 github 操作中捆绑安装私有(private) gem

python - 使用 Python 从加载的 XML 文件中获取 XML 文件名

ruby-on-rails - ActionMailer 最佳实践 : Call method in the model or the controller?

ruby-on-rails - rails 3 : How do I delay content submission so users can't spam rapidly?

ruby - 使用 ruby​​ 应用程序时出现 remove_entry_secure 错误

ruby-on-rails - Rails 4 activerecord更新多个属性

java - 在编码到 xml 文件之前计算 JAXB 输出流的校验和

python - 使用 ElementTree 在 Python 中解析 XML - findall

ruby-on-rails - Rails 3,来自连接表的数据

ruby-on-rails - 我是否在 RHEL 上正确安装了 Ruby 1.9.3?