I would like the node name in the following code to be "node:name" but instead the name is put into the text of the field.
require 'nokogiri'
file = File.new("/Users/user_a/code/xmler/test.xml", "w+")
builder = Nokogiri::XML::Builder.new do |xml|
xml.node:name do
end
end
file << builder.to_xml
file.close
puts builder.to_xml
How can I use the colon or other special characters in a node name with Nokogiri?
As I see it, you have three options:
You’re using namespaces
Then you can declare the namespace and use the
xml[]method:Output:
This method is a bit trickier if you want to add a namespace onto the root element though. See “How to create an XML document with a namespaced root element with Nokogiri Builder“.
You’re not using namespaces but want/need an element name with a colon:
In this case, you need to send the method named “node:name” to the
xmlblock parameter. You can do this with the normal rubysendmethod:this outputs:
You’re not sure what this “namespace” business is all about:
In this case you’re probably best avoiding using colons in your element names.
An alternative could be to use
-instead. If you did this you’d need to use method 2. above, but withxml.send 'node-name'. I include this option because you don’t mention namespaces in your question, and colons are used in them (as method 1. shows) so you’re safer not using colons to avoid any future problems.