Use XML parser : xmlparser « XML « Ruby






Use XML parser


require 'xmlparser'

class XMLRetry<Exception; end

class SampleParser<XMLParser
  private
  def startElement(name, attr)
    if name == "person"
       attr.each do |key, value|
         print "Found person of type #{value}.\n"
       end
    end
    if name == "name"
      $print_cdata = true
      self.defaultCurrent
    else
      $print_cdata = false

    end
  end

  def endElement(name)
    if name == "name"
      $print_cdata = false
    end
  end

  def character(data)
    if $print_cdata
      puts ("\tName is: #{data}")
    end
  end

end

xml = $<.read

parser = SampleParser.new
def parser.unknownEncoding(e)
  raise XMLRetry, e
end

begin
  parser.parse(xml)
rescue XMLRetry
  newencoding = nil
  e = $!.to_s
  parser = SampleParser.new(newencoding)
  retry
rescue XMLParserError
  line = parser.line
  print "Parse error(#{line}): #{$!}\n"
end

 








Related examples in the same category