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

17,974

Solution 1

Here you go:

require 'nokogiri'

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

puts b.to_xml

Solution 2

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

require 'nokogiri'

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

puts b.to_xml

Generates:

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

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

require 'nokogiri'

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

puts b.to_xml

Generates:

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

Solution 3

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:

require 'rubygems'
require 'nokogiri'

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

puts b.to_xml
Share:
17,974

Related videos on Youtube

Theozaurus
Author by

Theozaurus

Updated on August 07, 2020

Comments

  • Theozaurus
    Theozaurus almost 4 years

    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?

  • Satchel
    Satchel about 14 years
    where does the hello come in? xml.send(:"foo-bar", "hello")?
  • yegor256
    yegor256 almost 10 years
    Where is it documented in official Nokogiri documentation? can you please share a link?
  • bonh
    bonh over 9 years
  • Ghoti
    Ghoti about 7 years
    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