Chamnap
Chamnap

Reputation: 4766

Read and write xml file using Nokogiri

I'm newbie to Nokogiri ruby gem. I'm wondering how to read and write back to an xml file. The requirement is that I parse xml file, make some changes, and save it.

f = File.open("elevate.xml")
xml = Nokogiri::XML(f)
query = Nokogiri::XML::Node.new "query", xml
query["text"] = "bank"
query.parent = xml.root

f.close

This above code doesn't make any changes to that file at all. Do I have to create new file in order to save it back?

Upvotes: 2

Views: 5005

Answers (1)

mikej
mikej

Reputation: 66263

You can get the XML text of your document as a String using xml.to_xml and then write this to a file in the usual way.

Upvotes: 1

Related Questions