How to save my changes in XML file with Nokogiri
Asked Answered
B

1

16

I have the following simple XML file.

<?xml version="1.0"?>
<user-mapping>

</user-mapping>

I want to add content to the user mapping using Nokogiri.

This is my code:

f = File.open("exam.xml")
doc = Nokogiri::XML(f)
puts doc.to_s
map = doc.at_css "user-mapping"
map.content = "Gholam"
puts map.to_s
doc.to_xml
f.close

The output of the puts are:

<?xml version="1.0"?>
<user-mapping>

</user-mapping>
<user-mapping>Gholam</user-mapping>

But when the code ends, nothing has been change in the actual XML file. Can anyone explain to me how to save my changes in the XML file?

Bangkok answered 26/3, 2015 at 19:46 Comment(1)
Write the file to disk using standard Ruby convention. There is no special feature in Nokogiri for writing files.Thumb
R
23

Read the file into an in-memory XML document, modify the document as needed, then serialize the document back into the original file:

filename = 'exam.xml'
xml = File.read(filename)
doc = Nokogiri::XML(xml)
# ... make changes to doc ...
File.write(filename, doc)
Rosauraroscius answered 26/3, 2015 at 21:51 Comment(2)
Or File.write(filename, doc.to_xml)Simonton
to_xml is not needed, just File.write(filename, doc)Gobbler

© 2022 - 2024 — McMap. All rights reserved.