Ruby Unit Test : Is this a Valid (well-formed) XML Doc?

爱⌒轻易说出口 提交于 2019-12-01 17:18:22

You can use Nokogiri. It's not a standard Ruby library, but you can easily install it as a Gem.

begin
  bad_doc = Nokogiri::XML(badly_formed) { |config| config.options = Nokogiri::XML::ParseOptions::STRICT }
rescue Nokogiri::XML::SyntaxError => e
  puts "caught exception: #{e}"
end
# => caught exception: Premature end of data in tag root line 1

I use LibXML to perform xml validations, here is the basic usage:

require 'libxml'

# parse DTD
dtd = LibXML::XML::Dtd.new(<<EOF)
<!ELEMENT root (item*) >
<!ELEMENT item (#PCDATA) >
EOF

# parse xml document to be validated
instance = LibXML::XML::Document.file('instance.xml')

# validate
instance.validate(dtd) # => true | false

from LibXML::DTD

And this is a link to the LibXML documentation main page.

If you don't want to use your custom validation rules you can still use a public DTD with something like:

require 'open-uri'
dtd =  LibXML::XML::Dtd.new(open("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd").read)

of course you can do much better :)

rexml - build-in library. You can use a error handler to check your xml files

require 'rexml/document'
include REXML

errormsg = ''
doc = nil
begin
  doc = Document.new(File.new(filename))
rescue
  errormsg = $!
end

puts "Fail: #{errormsg}"   if('' != errormsg)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!