#33 Validating XML (xml_well_formedness_checker.rb)

All the XML processing in the world won’t do any good if your XML file is not well-formed. Since an XML document either is or is not well-formed, a well-formedness checker that will return either true or false seems like an ideal predicate method. Since XML documents are Files with Strings as their contents, we’ll add a well_formed_xml? method to both the File class and the String class.

The Code

  #!/usr/bin/env ruby
  # xml_well_formedness_checker.rb

  =begin rdoc
  This script uses the xml/dom/builder, written by YoshidaM.
  =end
❶ require 'xml/dom/builder'    The DOM class File ❷ def well_formed_xml?() read.well_formed_xml? end end class String ❸ def well_formed_xml?() builder = XML::DOM::Builder.new(0) ...

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.