tags:

views:

171

answers:

1

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?

A: 

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.

mikej
I suppose nokogiri could handle that automatically. Alright, that's maybe the only way to do it.
Chamnap
Details would be more helpful, but it is nice to know the .to_xml. Since Nokogiri seems to be appending to my file instead of replacing target as I'd expect.
Drew
@Drew what code are you using that results in an append rather than a replace?
mikej
The append is due to using File.open('path','r+').I found I had to open the file File.open('path','r'), then to modify the file I did a separate File.open('path','w').I couldn't find a way to use the same file pointer to do both reading and writing (r+ just appends)
Drew