How do I create XML using Nokogiri::XML::Builder with a hyphen in the element name?
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')endputs 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') }endputs b.to_xml
Generates:
<?xml version="1.0"?><foo-bar> <bar-foo>hello</bar-foo></foo-bar>
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' }endputs b.to_xml