ruby - Get all attributes for elements in XML file -
i'm trying parse file , of attributes each <row>
tag in file. file looks this:
<?xml version="1.0" standalone="yes"?> <report> <table> <columns> <column name="month"/> <column name="campaign"/> <!-- many columns --> </columns> <rows> <row month="december 2009" campaign="campaign #1" adgroup="python" preview="not available" headline="we write apps in python" and="many more attributes here" /> <row month="december 2009" campaign="campaign #1" adgroup="ruby" preview="not available" headline="we write apps in ruby" and="many more attributes here" /> <!-- many such rows --> </rows></table></report>
here full file: http://pastie.org/7268456#2.
i've looked @ every tutorial , answer can find on various boards assume same thing- i'm searching 1 or 2 specific tags , need 1 or 2 values tags. have 18 attributes each <row>
tag , have mysql table column each of 18 attributes. need put information object/hash/array can use insert table activerecord/ruby.
i started out using hpricot; can see code (which not relevant) in edit history of question.
require 'nokogiri' doc = nokogiri.xml(my_xml_string) doc.css('row').each |row| # row nokogiri::xml::element row.attributes.each |name,attr| # name string # attr nokogiri::xml::attr p name => attr.value end end #=> {"month"=>"december 2009"} #=> {"campaign"=>"campaign #1"} #=> {"adgroup"=>"python"} #=> {"preview"=>"not available"} #=> {"headline"=>"we write apps in python"} #=> etc.
alternatively, if want array of hashes mapping attribute names string values:
rows = doc.css('row').map{ |row| hash[ row.attributes.map{|n,a| [n,a.value]} ] } #=> [ #=> {"month"=>"december 2009", "campaign"=>"campaign #1", adgroup="python", … }, #=> {"month"=>"december 2009", "campaign"=>"campaign #1", adgroup="ruby", … }, #=> … #=> ]
the nokogiri.xml
method simplest way parse xml string , nokogiri::document
back.
the css
method simplest way find elements given name (ignoring containment hierarchy , xml namespaces). returns nokogiri::xml::nodeset
, similar array.
each nokogiri::xml::element
has attributes
method returns hash mapping name of attribute nokogiri::xml::attr
object containing information attribute (name, value, namespace, parent element, etc.)
Comments
Post a Comment