Rectangle 27 0

ruby How do I create XML using Nokogiri::XML::Builder with a hyphen in the element name?


require 'nokogiri'

b = Nokogiri::XML::Builder.new do |xml|
  xml.send(:"fooo-bar", "hello")
end

puts b.to_xml

Bit late to the party here, but that :"xx-aaa" syntax is the standard Ruby way of making a symbol when the syntax won't work for you

Where is it documented in official Nokogiri documentation? can you please share a link?

where does the hello come in? xml.send(:"foo-bar", "hello")?

Note
Rectangle 27 0

ruby How do I create XML using Nokogiri::XML::Builder with a hyphen in the element name?


require 'rubygems'
require 'nokogiri'

b = Nokogiri::XML::Builder.new do |xml|
  xml.send(:'foo.bar') {
    xml.text 'hello'
  }
end

puts b.to_xml

Aaron Patterson's answer is correct and will work for element names containing any character that may otherwise be interpreted by the Ruby parser.

Answering Angela's question: to place text inside a element created this way you can do something like this:

Note
Rectangle 27 0

ruby How do I create XML using Nokogiri::XML::Builder with a hyphen in the element name?


<?xml version="1.0"?>
<foo-bar>
  <bar-foo>hello</bar-foo>
</foo-bar>
require 'nokogiri'

b = Nokogiri::XML::Builder.new do |xml|
  xml.send(:'foo-bar') {
    xml.send(:'bar-foo', 'hello')
  }
end

puts b.to_xml

Bart Vandendriessche's answer works but there is a simpler solution if you only want a text field within the element.

If you need them to be nested then you can pass a block

Note
Rectangle 27 0

ruby How do I create XML using Nokogiri::XML::Builder with a hyphen in the element name?


require 'nokogiri'

b = Nokogiri::XML::Builder.new do |xml|
  xml.send(:"fooo-bar", "hello")
end

puts b.to_xml

Where is it documented in official Nokogiri documentation? can you please share a link?

where does the hello come in? xml.send(:"foo-bar", "hello")?

Note