Ruby 使用 xmlparser 解析 XML 信息

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

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