/tools/Ruby/lib/ruby/1.8/xsd/xmlparser/parser.rb

http://github.com/agross/netopenspace · Ruby · 96 lines · 65 code · 25 blank · 6 comment · 3 complexity · 33a96b0c0162381379e63ca73da1225c MD5 · raw file

  1. # XSD4R - XML Instance parser library.
  2. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
  3. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can
  4. # redistribute it and/or modify it under the same terms of Ruby's license;
  5. # either the dual license version in 2003, or any later version.
  6. require 'xsd/qname'
  7. require 'xsd/ns'
  8. require 'xsd/charset'
  9. module XSD
  10. module XMLParser
  11. class Parser
  12. class ParseError < Error; end
  13. class FormatDecodeError < ParseError; end
  14. class UnknownElementError < FormatDecodeError; end
  15. class UnknownAttributeError < FormatDecodeError; end
  16. class UnexpectedElementError < FormatDecodeError; end
  17. class ElementConstraintError < FormatDecodeError; end
  18. @@parser_factory = nil
  19. def self.factory
  20. @@parser_factory
  21. end
  22. def self.create_parser(host, opt = {})
  23. @@parser_factory.new(host, opt)
  24. end
  25. def self.add_factory(factory)
  26. if $DEBUG
  27. puts "Set #{ factory } as XML processor."
  28. end
  29. @@parser_factory = factory
  30. end
  31. public
  32. attr_accessor :charset
  33. def initialize(host, opt = {})
  34. @host = host
  35. @charset = opt[:charset] || nil
  36. end
  37. def parse(string_or_readable)
  38. @textbuf = ''
  39. prologue
  40. do_parse(string_or_readable)
  41. epilogue
  42. end
  43. private
  44. def do_parse(string_or_readable)
  45. raise NotImplementError.new(
  46. 'Method do_parse must be defined in derived class.')
  47. end
  48. def start_element(name, attrs)
  49. @host.start_element(name, attrs)
  50. end
  51. def characters(text)
  52. @host.characters(text)
  53. end
  54. def end_element(name)
  55. @host.end_element(name)
  56. end
  57. def prologue
  58. end
  59. def epilogue
  60. end
  61. def xmldecl_encoding=(charset)
  62. if @charset.nil?
  63. @charset = charset
  64. else
  65. # Definition in a stream (like HTTP) has a priority.
  66. p "encoding definition: #{ charset } is ignored." if $DEBUG
  67. end
  68. end
  69. end
  70. end
  71. end