我正在创建一个XML文档:我想至少进行单元测试以确保其格式正确。
到目前为止,我只能通过使用REXML库中的“hasElements”来近似这个值。
有没有更好的办法 ?
最好使用内置库(我的意思是标准Ruby 1.8.x发行版附带的库)。
require "test/unit"
require 'rexml/document'
require 'test/unit/ui/console/testrunner'
include REXML
class TestBasic < Test::Unit::TestCase
def test_createXML
my_xml=...create doc here...
doc = Document.new(my_xml);
assert(doc.has_elements?);
end
end
Test::Unit::UI::Console::TestRunner.run(TestBasic);
最佳答案
You can use Nokogiri。
它不是标准的Ruby库,但是您可以轻松地将其安装为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
关于xml - Ruby单元测试: Is this a Valid (well-formed) XML Doc?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2012786/