mgoblue92
mgoblue92

Reputation: 1

Ruby: Insert new XML element into existing XML file

How can I insert another XML element into an XML file I'm creating with Builder::XmlMarkup? e.g., something like

xml = Builder::XmlMarkup.new( :indent => 4 )

xml.content
    xml.common do
        xml.common_field1 do
            // common_field1 content
        end
        xml.common_field2 do
            // common_field 2 content
        end
    end
    xml.custom do 
        xml.insert!(<XML element>)
    end
end

Where <XML element> looks something like

<elements>
    <element>
        // element content
    </element>
    <element>
        // element content
    </element>
<elements>

and the final output looks like

<content>
 <common>
  <content1>
   <!-- content1 -->
  </content1>
  <content2>
   <!-- content2 -->
  </content2>
 </common>
 <custom>
  <elements>
   <element>
    <!-- element content -->
   </element>
   <element>
    <!-- element content -->
   </element>
  </elements>
 </custom>
</content>

I've tried using the << operator but that doesn't unfortunately doesn't maintain formatting.

Upvotes: 0

Views: 589

Answers (1)

Sofa
Sofa

Reputation: 319

<< is exactly what you need:

xml.custom do |custom|
    custom << '<XML element>'
end

Rubydocs doesn't seem to work, so here's the link to the source code: https://github.com/jimweirich/builder/blob/master/lib/builder/xmlbase.rb#L104

Upvotes: 1

Related Questions