如何使用Nokogiri保存我在XML文件中的更改

时间:2023-01-29 09:55:46

I have the following simple XML file.

我有以下简单的XML文件。

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

</user-mapping>

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

我想使用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?

但是当代码结束时,实际的XML文件中没有任何变化。任何人都可以向我解释如何在XML文件中保存我的更改?

1 个解决方案

#1


11  

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

将文件读入内存中的XML文档,根据需要修改文档,然后将文档序列化回原始文件:

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

#1


11  

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

将文件读入内存中的XML文档,根据需要修改文档,然后将文档序列化回原始文件:

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