k_Dank
k_Dank

Reputation: 695

Ruby - Iterating over xml elements with same name but distinct meaning using NokoGiri

I am using the UPS API to validate locations. I receive the XML response from UPS then try to parse out the information I need. UPS can send back one to three <AddressLine> elements per address, depending on the address.

If an address has two or more AddressLines, I need to pull out the first two. If an address has only one AddressLine, I need to pull that one line.

How can I pull out address and address2?

<AddressKeyFormat>
  <AddressLine>655 MANSELL RD</AddressLine>
  <AddressLine>Apartment #2</AddressLine>
</AddressKeyFormat>

The code :

xml.xpath('//AddressKeyFormat').each do |node|
  #pull out address, and address2
end

Upvotes: 1

Views: 538

Answers (2)

Mark Thomas
Mark Thomas

Reputation: 37527

This will give you a maximum of two addresslines:

xml.xpath('//AddressKeyFormat/AddressLine').map(&:text)[0,2]

Upvotes: 1

maerics
maerics

Reputation: 156682

Assuming that xml is a Nokogiri XML document (e.g. xml = Nokogiri::XML(xmlString)) you can do an XPath search for //AddressLine and the result will be all of those nodes:

xml.xpath('//AddressLine').map(&:text) # => ["655 MANSELL RD", "Apartment #2"] 

Upvotes: 4

Related Questions