1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#! /usr/local/bin/ruby
require 'xmlparser'
require 'nkf'
require 'uconv'
class XMLRetry<Exception; end
class SampleParser<XMLParser
def startElement(name, attr)
line = self.line
column = self.column
byteIndex = self.byteIndex
print "L#{line}, #{column}, #{byteIndex}\n"
attr.each do |key, value|
print Uconv.u8toeuc("A#{key} CDATA #{value}\n")
end
print Uconv.u8toeuc("(#{name}\n")
self.defaultCurrent
end
private :startElement
def endElement(name)
print Uconv.u8toeuc(")#{name}\n")
end
private :endElement
def character(data)
data.gsub!("\n", "\\n")
print Uconv.u8toeuc("-#{data}\n")
end
private :character
def processingInstruction(target, data)
data.gsub!("\n", "\\n")
print Uconv.u8toeuc("?#{target} #{data}\n")
end
private :processingInstruction
def default(data)
return if data =~ /^<\?xml /
data.gsub!("\n", "\\n")
print Uconv.u8toeuc("//#{data}\n")
end
private :default
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
if e =~ /^iso-2022-jp$/i
xml = NKF.nkf("-Je", xml)
newencoding = "EUC-JP"
end
parser = SampleParser.new(newencoding)
retry
rescue XMLParserError
line = parser.line
print "Parse error(#{line}): #{$!}\n"
end
|