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

I am creating an XML document: I want to unit test at least to make sure it is well formed. So far, I could only approximate this using the "hasElements" in the REXML library.

Is there a better way? It is preferable to use the built-in libraries (I mean the libraries that come with the standard Ruby 1.8.x distribution).

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);
+5
source share
3 answers

You can use Nokogiri . This is 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
+11
source

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)

, :)

+2

rexml- built-in library. You can use an error handler to validate 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)
0
source

All Articles