Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building blank XML tags with Nokogiri?

Tags:

xml

ruby

nokogiri

I'm trying to build up an XML document using Nokogiri. Everything is pretty standard so far; most of my code just looks something like:

builder = Nokogiri::XML::Builder.new do |xml|
    ...
    xml.Tag1(object.attribute_1)
    xml.Tag2(object.attribute_2)
    xml.Tag3(object.attribute_3)
    xml.Tag4(nil)
  end

builder.to_xml

However, that results in a tag like <Tag4/> instead of <Tag4></Tag4>, which is what my end user has specified that the output needs to be.

How do I tell Nokogiri to put full tags around a nil value?

like image 821
Bryce Avatar asked Dec 19 '13 15:12

Bryce


1 Answers

SaveOptions::NO_EMPTY_TAGS will get you what you want.

require 'nokogiri'

builder = Nokogiri::XML::Builder.new do |xml|
  xml.blah(nil)
end

puts 'broken:'
puts builder.to_xml
puts 'fixed:'
puts builder.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS)

output:

(511)-> ruby derp.rb 
broken:
<?xml version="1.0"?>
<blah/>
fixed:
<?xml version="1.0"?>
<blah></blah>
like image 71
Nick Veys Avatar answered Nov 02 '22 04:11

Nick Veys