Naming a Text Element with Nokogiri and Ruby

I have a little problem trying to create an XML document using Nokogiri.

I want to name one of my text elements (see the very bottom of the pasted code below). Usually, to create a new element, I do something like the following xml.text - but it seems that .text is a method already used by Nokogiri to do something else. Thus, when I write this line xml.text , Nokogiri does not create a new element called <text> , but simply writes text intended for the content of the element. How can I get Nokogiri to create an element named <text> ?

 builder = Nokogiri::XML::Builder.new do |xml| xml.TEI("xmlns" => "http://www.tei-c.org/ns/1.0"){ xml.teiHeader { xml.fileDesc{ xml.titleStmt{ xml.title "Version Log for #{title}" xml.author "Jeffrey C. Witt" } xml.editionStmt{ xml.edition('n' => "#{ed_no}") { xml.date('when' => "#{newDate}") } } xml.publicationStmt{ xml.publisher "#{publisher}" xml.pubPlace "#{pubPlace}" xml.availability("status" => "free") { xml.p "Published under a Creative Commons Attribution ShareAlike 3.0 License" } xml.date("when" => "#{newDate}") } xml.sourceDesc { xml.p "born digital" } } } xml.text "test"{ xml.body { xml.p "test document } } } 
+4
source share
1 answer

From docs :

The builder works using the method_missing method. Unfortunately, some methods are defined in ruby โ€‹โ€‹that are difficult or dangerous to remove. You might want to create tags with the names "type", "class" and "id", for example. In this case, you can use the underscore to disambiguate the tag name from the method call.

So, all you have to do is add an underscore after text , for example:

 builder = Nokogiri::XML::Builder.new { |xml| xml.text_ "test" } builder.to_xml #=> "<?xml version=\"1.0\"?>\n<text>test</text>\n" 
+10
source

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


All Articles