Ruby 单元测试:这是一个有效(格式良好)的 XML 文档吗? [英] Ruby Unit Test : Is this a Valid (well-formed) XML Doc?

查看:46
本文介绍了Ruby 单元测试:这是一个有效(格式良好)的 XML 文档吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 XML 文档:我想至少进行单元测试以确保它的格式正确.到目前为止,我只能通过使用 REXML 库中的hasElements"来近似这一点.

I'm creating an XML document: I want to unit test at least to make sure it's well-formed. So far, I have only been able to approximate this , by using the 'hasElements' in the REXML library.

有更好的方法吗?最好使用内置库(我的意思是标准 Ruby 1.8.x 发行版附带的库).

Is there a better way ? Preferably using built-in libraries (I mean libraries that ship with the standard Ruby 1.8.x distro).

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);

推荐答案

你可以使用 Nokogiri.它不是标准的 Ruby 库,但您可以轻松地将其安装为 Gem.

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

这篇关于Ruby 单元测试:这是一个有效(格式良好)的 XML 文档吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆