Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a colon (":") in a Nokogiri node name

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?

like image 385
OpenCoderX Avatar asked Feb 19 '12 17:02

OpenCoderX


2 Answers

As I see it, you have three options:

  1. 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".

  2. 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>
    
  3. 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.

like image 107
matt Avatar answered Oct 01 '22 19:10

matt


builder = Nokogiri::XML::Builder.new do  |xml|
  xml.send("foo:bar") do
  end
end


?> puts builder.to_xml
<?xml version="1.0"?>
<foo:bar/>
like image 20
jdl Avatar answered Oct 01 '22 19:10

jdl