...">

How to save changes to an XML file using Nokogiri

I have the following simple XML file.

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

I want to add content to a custom 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 puts :

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

But when the code ends, nothing has changed in the actual XML file. Can someone explain to me how to save changes to the XML file?

+6
source share
1 answer

Read the file in the XML document in memory, modify the document as necessary, and then serialize the document to the source file:

 filename = 'exam.xml' xml = File.read(filename) doc = Nokogiri::XML(xml) # ... make changes to doc ... File.write(filename, doc.to_xml) 
+11
source

Source: https://habr.com/ru/post/984285/


All Articles