Using Nokogiri to create an XML element with a namespace

I use Nokogiri, which would create XML. I want to have the following structure:

<content:encode>text</content>

I tried this code:

xml.content['encoded'] {xml.text "text"}

but it gives me an error.

How do I spell this correctly? A similar example is given in Link to declared namespaces .

+3
source share
1 answer
  • Your example does not make sense; you say you want to β€œencode” and then try to write β€œencoded”.

  • , XML. encode content, content. <content:encode>text</content:encode>, <encode:content>text</encode:content>. ( ?)

  • . content encoded, , :

    xml['encoded'].content{ xml.text "text" }
    
  • , , , . :

    require 'nokogiri'
    
    builder = Nokogiri::XML::Builder.new do |xml|
      xml.root('xmlns:encoded' => 'bar') do
        xml['encoded'].content{ xml.text "text" }
      end
    end
    puts builder.to_xml
    #=> <?xml version="1.0"?>
    #=> <root xmlns:encoded="bar">
    #=>   <encoded:content>text</encoded:content>
    #=> </root>
    

. , Nokogiri . :

str = "Hello World"
xml = "<encoded:content>#{str}</encoded:content>"
puts xml
#=> <encoded:content>Hello World</encoded:content>

Nokogiri, - , :

xml_str = builder.doc.root.children.first.to_s
#=> "<encoded:content>text</encoded:content>"
+10

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


All Articles