I need to parse a xml document in ruby, using rexml, that has the following structure:
<events>
<event>
<title>Best NYC New Year's Party</title>
<description>Come spend New Year's Eve with us!</description>
<category>conferences</category>
<tags>new year, party</tags>
<start_date>2008-12-31 20:00:00</start_date>
<end_date>2009-01-01 06:00:00</end_date>
<venue>
<name>Madison Square Garden</name>
<address>4 Penn Plaza</address>
<city>New York</city>
<country>United States</country>
</venue>
</event>
</events>
I use this code to get the title and description elements:
doc_xml.elements.each("events/event") do |element|
event = Event.new
event.title = element.elements["title"].text
event.description = element.elements["description"].text
I tried event.address = element.elements["venue"].elements["address"] but I get undefined method `elements’ for nil:NilClass.
But how can I access name element inside venue element?
try this
because you should only use the text method if “venue” has an element “address”, otherwise nil is returned.
you can get the “name” element in the same way:
if you have to do more complex things with the XML, I recommend using a parser like nokogiri