M
M
Michael2021-01-23 17:46:08
ruby
Michael, 2021-01-23 17:46:08

How to properly parse and create nested_attribute from xml?

Dear experts, here is the question:
There is some xml, you need to take data from xml from it and create a nested_attribute

<engines>
    <engine>
      <id>24</id>
      <properties>
        <property>
          <id_property>15</id_property>
          <value>1013</value>
        </property>
        <property>
          <id_property>13</id_property>
          <value>Рядный</value>
        </property>
        <property>
          <id_property>12</id_property>
          <value>4</value>
        </property>
        <property>
          <id_property>10</id_property>
          <value>4.76</value>
        </property>
        <property>
          <id_property>4</id_property>
          <value>74</value>
        </property>
        <property>
          <id_property>14</id_property>
          <value>Жидкостное охлаждение</value>
        </property>
        <property>
          <id_property>11</id_property>
          <value>Tier 2</value>
        </property>
        <property>
          <id_property>7</id_property>
          <value>430</value>
        </property>
      </properties>
    </engine>
</engines>


engines = @doc.xpath('/catalog/engines/engine')
engines.map do |engine|

id_property = engine.xpath('properties/property/id_property').map do |id_property|
  id_property.text.strip
end

value = engine.xpath('properties/property/value').map do |value|
  value.text.strip
end

values_attributes = [id_property, value]

puts values_attributes:
[id_property, value].transpose
  {
    property_id: id_property,
    property_value: value
  }
end


The code above produces this:
{:values_attributes=>}

Required:
values_attributes: [ {property_id:'1', property_value:'2'}, {property_id:'2', property_value:'3'}]

How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2021-01-23
@mirbook

engines = @doc.xpath('/catalog/engines/engine').map do |engine|
  {
    values_attributes: engine.xpath('properties/property').map do |property|
      {
        property_id: property.xpath('id_property').text.strip,
        property_value: property.xpath('value').text.strip
      }
    end
  }
end
puts engines
{:values_attributes=>[{:property_id=>"15", :property_value=>"1013"}, {:property_id=>"13", :property_value=>"Рядный"}, {:property_id=>"12", :property_value=>"4"}, {:property_id=>"10", :property_value=>"4.76"}, {:property_id=>"4", :property_value=>"74"}, {:property_id=>"14", :property_value=>"Жидкостное охлаждение"}, {:property_id=>"11", :property_value=>"Tier 2"}, {:property_id=>"7", :property_value=>"430"}]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question