How to use colon: in nokogiri node name?

I would like the node name in the following code to be "node: name", but instead the name is placed in the text of the field.

require 'nokogiri' file = File.new("/Users/adamar/code/xmler/test.xml", "w+") builder = Nokogiri::XML::Builder.new do |xml| xml.node:name do end end file << builder.to_xml puts builder.to_xml 

How can I use a colon or other special characters in a node name using nokogiri?

+6
source share
2 answers

As I can see, you have three options:

1. You are 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 

Conclusion:

 <root xmlns:node="http://example.com"> <node:name/> </root> 

This method is a bit more complicated if you want to add a namespace to the root element, but see Creating an XML document with a root element with a namespace with the Nokogiri constructor .

2. You do not use namespaces, but want / need a colon element name

In this case, you need to send a method named "node: name" to the xml block parameter. You can do this with the usual ruby โ€‹โ€‹send method:

 builder = Nokogiri::XML::Builder.new do |xml| xml.root do xml.send 'node:name' end end 

these outputs:

 <?xml version="1.0"?> <root> <node:name/> </root> 

3. You do not know what a "namespace" is - it's all about

In this case, your best bet is to avoid using colons in the names of your elements. An alternative could be to use - . If you have done this, you will need to use method 2 above, but with xml.send 'node-name' . I enable this option because you do not specify namespaces in your question and they use colons (as method 1 shows), so you cannot use a colon to avoid any future problems.

+10
source
 builder = Nokogiri::XML::Builder.new do |xml| xml.send("foo:bar") do end end ?> puts builder.to_xml <?xml version="1.0"?> <foo:bar/> 
+1
source

Source: https://habr.com/ru/post/908837/


All Articles