ontology_parser.rb revision 3e7a51349781a4cf69b876a1488db647bb62a63d
# Parses the given string and executes the callback for each symbol
# Create a new parser
# Feed the parser some XML
end
# Listener for the SAX Parser
ROOT = 'DGraph'
ONTOLOGY = 'DGNode'
SYMBOL = 'Symbol'
AXIOM = 'Axiom'
LINK = 'DGLink'
# the callback function is called for each Symbol tag
@path = []
@current_axiom = nil
end
# a tag
@path << name
case name
when ROOT
callback(:root, Hash[*[attributes]])
when ONTOLOGY
callback(:ontology, Hash[*[attributes]])
when SYMBOL
@current_symbol = Hash[*[attributes]]
@current_symbol['text'] = ''
when AXIOM
@current_axiom = Hash[*[attributes]]
@current_axiom['symbols'] = []
@current_axiom['text'] = ''
when LINK
@current_link = Hash[*[attributes]]
else
# NOTHING
end
end
# a text node
def characters(text)
case @path.last
when SYMBOL
@current_symbol['text'] << text if @current_symbol
when AXIOM
@current_axiom['text'] << text if @current_axiom
end
end
# closing tag
def end_element(name)
@path.pop
case name
when ONTOLOGY
callback(:ontology_end, @current_ontology)
@current_ontology = nil
when SYMBOL
return if @path.last == 'Hidden'
if @current_axiom
# add to current axiom
@current_axiom['symbols'] << @current_symbol['text']
else
# return the current symcol
callback(:symbol, @current_symbol)
end
@current_symbol = nil
when AXIOM
# return the current axiom
callback(:axiom, @current_axiom)
@current_axiom = nil
when LINK
# return the current link
callback(:link, @current_link)
@current_link = nil
end
end
# error handler for parsing problems
def error(string)
raise ParseException, 'cannot parse: ' + string
end
private
def callback(name, args)
block = @callbacks[name]
block.call(args) if block
end
end
end