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:
builder = Nokogiri::XML::Builder.new do |xml|
xml.root('xmlns:node' => 'http://example.com') do
xml['node'].name
end
end
Output:
<root xmlns:node="http://example.com">
<node:name/>
</root>
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 xml
block parameter. You can do this with the normal ruby send
method:
builder = Nokogiri::XML::Builder.new do |xml|
xml.root do
xml.send 'node:name'
end
end
this outputs:
<?xml version="1.0"?>
<root>
<node:name/>
</root>
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 with xml.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.
builder = Nokogiri::XML::Builder.new do |xml|
xml.send("foo:bar") do
end
end
?> puts builder.to_xml
<?xml version="1.0"?>
<foo:bar/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With