ruby on rails - Nokogiri XML file output is located where? -
i need generate xml file ruby and/or rails , have nokogiri installed.
- in file ruby code go generate xml file?
- how tell nokogiri generate xml , put file?
- where xml output located?
here code 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') |xml| xml.root { xml.products{ xml.widget { xml.id_ "10" xml.name "awesome widget" } } } doc = nokogiri::xml.parse(params) file.open('xml.out', 'w') |fo| fo.print doc.to_s end end puts builder.to_xml end end
i need basic understanding of structure of ruby , rails applications , how nokogiri works.
to generate xml file not need rails. ruby (and nokogiri or oder builder) suffice.
first, have build xml:
builder = nokogiri::xml::builder.new(:encoding => 'utf-8') |xml| xml.root xml.products xml.widget xml.id_ "10" xml.name "awesome widget" end end end end
you can xml string 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 string file, use file.open
, file#write
:
# open file instance path '/path/to/file.xml' in write mode (-> 'w') file.open('/path/to/file.xml', 'w') |file| # write xml string generated above file file.write xml_string end
an important note: have make sure close files opened if no longer need them. file.open
block (as used in snipped above) automatically close file after code in block executed...
Comments
Post a Comment