我正在尝试使用 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/