ruby-on-railsxmlxml-builder

rails 3 XML builder: return no XML element when there's no data


I get this nice XML when there's data in the fields:

<DescriptiveDetail>
  <ProductComposition>00</ProductComposition>
  <ProductForm>01</ProductForm>
  <Measure>
    <MeasureType>01</MeasureType>
    <MeasureType>198</MeasureType>
    <MeasureType>mm</MeasureType>
  </Measure>
</DescriptiveDetail>

And when there isn't data, I'd like to get this:

<DescriptiveDetail>
  <ProductComposition>00</ProductComposition>
</DescriptiveDetail>

But instead I'm getting this:

<DescriptiveDetail>
  <ProductComposition></ProductComposition>
  <ProductForm></ProductForm>
  <Measure>
    <MeasureType></MeasureType>
    <MeasureType></MeasureType>
    <MeasureType></MeasureType>
  </Measure>
</DescriptiveDetail>

How do I return no XML element when there's no data?

(And just out of interest, if you know, how do you return a self closing tag, e.g.

<Measure/>

)

Here's my XML builder code (in full, the relevant bit is in the middle):

xml.instruct!(:xml, :encoding => "ISO-8859-1")
xml.ONIXMessage(:release=>"3.0") do
  xml.Header do
    xml.Sender
      xml.SenderName 
  end
  @isbnlist.each do |isbn|
    xml.Product do
      xml.RecordReference isbn.id
      xml.NotificationType isbn.notificationtype
        isbn.productcodes.each do |productcode|
          xml.ProductIdentifier do 
            xml.ProductIDType productcode.idtype
            xml.IDValue productcode.idvalue
          end
        end
      xml.DescriptiveDetail do
        xml.ProductComposition isbn.descriptivedetail_productcomposition_productcomposition
        xml.ProductForm isbn.descriptivedetail_productcomposition_productform
          isbn.measurements.each do |measurement|
            xml.Measure do
              xml.MeasureType measurement.descriptivedetail_measure_measuretype 
              xml.MeasureType measurement.descriptivedetail_measure_measurement 
              xml.MeasureType measurement.descriptivedetail_measure_measureunitcode
            end 
          end  
        xml.TitleDetail do
          xml.TitleType isbn.descriptivedetail_titledetail_titletype
            xml.TitleElement do
              xml.TitleElementLevel isbn.descriptivedetail_titledetail_titleelement_titleelementlevel
              xml.TitlePrefix isbn.descriptivedetail_titledetail_titleelement_titleprefix
              xml.TitleWithoutPrefix isbn.descriptivedetail_titledetail_titleelement_titlewithoutprefix
            end 
          xml 
        end 
        end 
      end
    end
  end

Solution

  • Have you tried just to check if @isbnlist is empty, and if so, use a conditional statement to either iterate through all the elements or just print out the short / empty version?