Hunter McMillen
Hunter McMillen

Reputation: 61520

Ruby XML syntax error

I am trying to evaluate 4 XML files that I create from a mysql database, I want to output the text of those XML field as a pairs of data so I can create a hash. (Ex: "Total Builds, 359") I am pretty sure I am getting a syntax error because of the way I am using the block

Here is what I am trying to do:

  while i < numberOfFiles do
            #create a document
            doc = Document.new(File.new(filenames[i]))
            doc.elements.each("//row/field")
            {
             |e|  ##Syntax error here
             name = e.attributes['name']
             text = e.text
             if name == "Total Builds"
                    puts name + ", " + text
             elsif name == "Successful Builds"
                    puts name + ", " + text
             elsif name == "Failed Builds"
                    puts name + ", " + text
             else
                    puts text.join(",")
             end
            }

I know that the format of this block is wrong, but is there a way to do something similar to this in ruby?

Thanks

Upvotes: 1

Views: 92

Answers (1)

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31438

I don't see why it would cause a syntax error but you are mixing do end and curly braces. I recommend that you don't, at least not for such a long block.

Try something like

doc.elements.each("//row/field") do |element|
  name = element.attributes['name']
  text = element.text
  builds = ["Total Builds", "Successful Builds", "Failed Builds"]
  if builds.include?(name)
    puts name + ", " + text
  else
    puts text.join(",")
  end
end

Also, while statements like that are not how it's usually done in Ruby. Often it's something like:

filenames.each do |filename|
  doc = Document.new(File.new(filename))

Upvotes: 1

Related Questions