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

rexml, ruby, unit-testing, xml

Solution

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

Problem

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

Original source