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

Theozaurus picture Theozaurus · Dec 22, 2009 · Viewed 16.6k times · Source

I am trying to build an XML document using Nokogiri. Some of the elements have hyphens in them. Here's an example:

require "nokogiri"
builder = Nokogiri::XML::Builder.new do |xml|
  xml.foo_bar "hello"
end

puts builder.to_xml

Which produces:

<?xml version="1.0"?>
<foo_bar>hello</foo_bar>

However, when I try:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.foo-bar "hello"
end

I get:

syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
  xml.foo-bar "hello"

Now I realise this is because the hyphen is being interpreted as foo MINUS bar.

How should I do this?

Answer

Aaron Patterson picture Aaron Patterson · Dec 22, 2009

Here you go:

require 'nokogiri'

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

puts b.to_xml