Answer to Best of Ruby Quiz quiz 03
Answer to "GEDCOM Parser"version 1
require "rexml/document"
include REXML
Global_pattern = /\S+/
Id_pattern = /\@(.*)\@/
Tag_pattern = /[A-Z]{3,4}/
doc = node = Document.new
previous_level = -1
def convert_to_node(doc, line)
cool = line.scan(Global_pattern)
if cool[1].match(Tag_pattern)
node = doc.add_element(cool[1])
node.text = cool[2..-1].join(" ")
elsif cool[1].match(Id_pattern)
if cool[2].match(Tag_pattern)
node = doc.add_element(cool[2])
node.add_attribute("id", cool[1])
else
exit
end
else
exit
end
end
file = File.open("hello03")
#root = node.add_element("ok" + file.gets()[0].chr)
convert_to_node(node, file.gets())
file.each do |line|
line_num = line[0].chr.to_i
if previous_level < line_num
if line_num - previous_level == 2
node = node.elements[node.elements.size]
# node.add_element("ok" + line_num.to_s)
convert_to_node(node, line)
previous_level += 1
elsif line_num - previous_level == 1
# node.add_element("ok" + line_num.to_s)
convert_to_node(node, line)
end
else
(previous_level - line_num + 1).times do
node = node.parent
end
previous_level = line_num - 1
# node.add_element("ok" + line_num.to_s)
convert_to_node(node, line)
end
end
File.open("cool005.xml","w") do |file|
doc.elements.each do |line|
file.puts line
end
end