6

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.

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

3 回答 3

12

您可以使用 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
于 2010-01-06T12:50:52.017 回答
3

我使用 LibXML 来执行 xml 验证,这里是基本用法:

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

来自LibXML::DTD

这是LibXML 文档主页的链接。

如果您不想使用自定义验证规则,您仍然可以使用公共 DTD,例如:

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

当然你可以做得更好:)

于 2010-01-06T12:32:23.760 回答
0

rexml- 内置库。您可以使用错误处理程序来检查您的 xml 文件

require 'rexml/document'
include REXML

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

puts "Fail: #{errormsg}"   if('' != errormsg)
于 2014-12-05T23:13:07.877 回答