ironmantis7x
ironmantis7x

Reputation: 827

Nokogiri XML file output is located where?

I need to generate an XML file with Ruby and/or Rails and have Nokogiri installed.

  1. In what file does the Ruby code go that will generate the XML file?
  2. How do I tell Nokogiri to generate the XML and put it into a file?
  3. Where is the XML output located?

Here is my code from my controller file:

class MonkeyTalkController < ApplicationController

require 'rubygems'
require 'nokogiri'

  def edit

  end

  def update
#debugger
    render :text => MonkeyTalk.new(params).build_xml

    builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
      xml.root {
  xml.products{
         xml.widget {
          xml.id_ "10"
          xml.name "Awesome widget"
          }
        }
      }

      doc = Nokogiri::XML.parse(params)
      File.open('xml.out', 'w') do |fo|
      fo.print doc.to_s
      end
    end
    puts builder.to_xml

  end

end

I need a basic understanding of the structure of Ruby and Rails applications and how Nokogiri works.

Upvotes: 2

Views: 2787

Answers (2)

Phrogz
Phrogz

Reputation: 303361

Your file was written to xml.out. Where is this file? It depends on what the working directory was when you started your application, and whether your code or any library ever called Dir.chdir to change the working directory.

You can output Dir.pwd or File.expand_path('xml.out') to see where this file was written.

Upvotes: 0

severin
severin

Reputation: 10268

To generate an xml file you do not need Rails. Ruby (and Nokogiri or some oder builder) will suffice.

First, you have to build your xml:

builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
  xml.root do
    xml.products do
      xml.widget do
        xml.id_ "10"
        xml.name "Awesome widget"
      end
    end
  end
end

You can get an xml string from this builder using builder.to_xml:

xml_string = builder.to_xml # => "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <products>\n    <widget>\n      <id>10</id>\n      <name>Awesome widget</name>\n    </widget>\n  </products>\n</root>\n"

To save this string into a file, you use File.open and File#write:

# open a file instance with path '/path/to/file.xml' in write mode (-> 'w')
File.open('/path/to/file.xml', 'w') do |file|
  # write the xml string generated above to the file
  file.write xml_string
end

An important note: you always have to make sure that you close all files that you opened if you no longer need them. File.open with a block (as used in my snipped above) will automatically close the file for you after the code in the block is executed...

Upvotes: 6

Related Questions