Walker
Walker

Reputation: 5189

Ruby - Finding Elements with REXML

I have an XML file that holds information about retail stores in a particular city and their locations but I'm having some trouble retrieving data from it. The problem is I can find stores by their names by looping through the name elements but I don't know how to get the corresponding addresses once I find the stores I'm looking for. Does anyone know how to do this? I'm using REXML as my main XML module. Here's what my XML file and my code look like

XML:

<stores>
  <store>
    <name>Supermarket</name>
    <address>2136 56th Avenue</address>
  </store>
  <store>
    <name>Convenience Store</name>
    <address>503 East Avenue</address>
  </store>
  <store>
    <name>Pharmacy</name>
    <address>212 Main Street</address>
  </store>
</stores>

Ruby:

xml_file.elements.each('stores/store/name') do |name|
  if input == name
    print name + "\n"
    #code to retrieve the address
    print address + "\n\n"
  end
end

Upvotes: 1

Views: 6655

Answers (2)

Sully
Sully

Reputation: 14943

xml_file = Document.new File.new("myxml.xml")

xml_file.elements.each("stores/store") do |element| 
  if element.attributes["name"] == input
    puts element.attributes["address"]
  end
end

attributes are for

<store store_name="mystore" 

to get

element.attributes["store_name"]

Edit, sorry try this

xml_file.elements.each("stores/store") do |element| 
  if element.name.text == input
    puts element.address.text
  end
end

Based on comment, the correct syntax is dialog.elements['name'].text

Upvotes: 3

csalzman
csalzman

Reputation: 61

Here's my take. '//name/..' selects the parent node of the all the 'name' nodes. The if statement is checking the text of the name node against your input (matched_names in this example). Display or store the name and address data as you will in the rest of the block:

matched_names = ['Convenience Store', 'Pharmacy']

doc.elements.each('//name/..') do |parent|
  if (matched_names.include? parent.elements['name/text()'].to_s)
    puts parent.elements['name']
    puts parent.elements['address']
  end
end

Upvotes: 1

Related Questions