Ruby 编辑并保存相同的xml文件
我已经编写了一段代码,删除了xml文件上的注释,如何再次将其保存为xml文件。目前,我将xml文件读取为文本文件。当我在控制台上运行此代码时,它会输出xml内容,但在newexample.xml上它会打印出以下内容:Ruby 编辑并保存相同的xml文件,ruby,xml,Ruby,Xml,我已经编写了一段代码,删除了xml文件上的注释,如何再次将其保存为xml文件。目前,我将xml文件读取为文本文件。当我在控制台上运行此代码时,它会输出xml内容,但在newexample.xml上它会打印出以下内容:**如何将其打印为xml文件?请帮忙 编辑前的xml <!-- <product> <name>PC</name> <price>R100</price> </produ
**
如何将其打印为xml文件?请帮忙
编辑前的xml
<!--
<product>
<name>PC</name>
<price>R100</price>
</product>
-->
你可以
#!/usr/bin/env ruby
file_path = 'C:/ruby/example.xml'
File.open(file_path, 'r') do |file|
@a = file.map{ |line| line.gsub(/^\s\W*\s$/, " ") }
end
File.open(file_path, 'w') do |file|
@a.each { |e| file.puts e }
end
提供示例输入和预期输出。@konsolebox我已经编辑了我的文章
file = File.open('C:/ruby/example.xml','r+') do |file|
file.each {|line| line.gsub(/^\s\W*\s$/, " ")}
end
File.open("newexample.xml","w") do |f|
f.write file
end
#!/usr/bin/env ruby
file_path = 'C:/ruby/example.xml'
File.open(file_path, 'r') do |file|
@a = file.map{ |line| line.gsub(/^\s\W*\s$/, " ") }
end
File.open(file_path, 'w') do |file|
@a.each { |e| file.puts e }
end