Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming element "text" with Nokogiri and Ruby

Tags:

ruby

nokogiri

I have a small problem when trying build an XML document with Nokogiri.

I want to call one of my elements "text" (see the the very bottom of the pasted code below). Normally, to create a new element I do something like the following xml.text -- but it seems to be .text is a method already used by Nokogiri to do something else. Thus when I write this line xml.text Nokogiri is not creating a new element called <text> but is just writing the text meant to be the content of the element. How can I get Nokogiri to actually make an element called <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
       }
     }
  }
like image 488
Jeff Avatar asked Nov 23 '12 14:11

Jeff


1 Answers

From the docs:

The builder works by taking advantage of method_missing. Unfortunately some methods are defined in ruby that are difficult or dangerous to remove. You may want to create tags with the name “type”, “class”, and “id” for example. In that case, you can use an underscore to disambiguate your tag name from the method call.

So, all you have to do is add an underscore after text, like so:

builder = Nokogiri::XML::Builder.new { |xml| xml.text_ "test" }
builder.to_xml
#=> "<?xml version=\"1.0\"?>\n<text>test</text>\n"
like image 60
Chris Salzberg Avatar answered Oct 22 '22 06:10

Chris Salzberg