user user - 4 months ago 6
Ruby Question

How to nest params using Nokogiri

I want to create XML like this:

<categories>
<category id=1>Sound</category>
<category id=2 parentId=1>Speakers</category>
</categories>


I used:

require 'nokogiri'
@builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
xml.categories{
Category.all.each do |c|
xml.category# here i should insert my needs

end
}
}
end


I used an example from "docs about Tag Attribute Short Cuts" but it gave me
class
and
id
instead what I want.

How do I do it properly?

Answer

can you try below code, it will add the id attribute to the category tag.

require 'nokogiri'
  @builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.categories{
       Category.all.each do |c|
         xml.category(c.name, "id" => c.id)
  end
  }
}
end

Output should be like.

<categories>
 <category id=1>Sound</category>
 <category id=2>Speakers</category>
</categories
Comments