我的文件越来越短,我不知道为什么

时间:2011-07-27 12:52:05

标签: ruby

我有一个要求,我需要编辑部分xml文件并保存,但在我的代码中,xml文件的某些部分没有保存。我想将<mtn:ttl>4</mtn:ttl>修改为<mtn:ttl>9</mtn:ttl>,这部分是在下面的代码中进行修改但是当写入/保存文件的一部分变得很乱或文件的格式变得混乱时,任何人都可以告诉我如何解决这个问题吗?原始xml文件大小为79kb,但编辑并保存后变为78kb ......

require "rexml/text"
require "rexml/document"
include REXML
File.open("c://conf//cad-mtn-config.xml") do |config_file|
  # Open the document and edit the file
  config = Document.new(config_file)
  if testField.to_s.match(/<mtn:ttl>/)
    config.root.elements[4].elements[11].elements[1].elements[1].elements[1].elements[8].text="9"
    # Write the result to a new file.
    formatter = REXML::Formatters::Default.new
    File.open("c://mtn-3//mtn-2.2//conf//cad-mtn-config.xml", 'w') do |result|
      formatter.write(config, result)
    end
  end
end

1 个答案:

答案 0 :(得分:1)

看起来你试图使用正则表达式,为什么不使用rexml?唯一的要求是您需要知道命名空间在线的位置。请注意,如果它不是mtn:ttl而只是ttl,则不需要命名空间。

require 'rexml/document'

file_path="path to file"
contents=File.new(file_path).read

xml_doc=REXML::Document.new(contents)
xml_doc.add_namespace('mtn',"http://url to mtn namespace")
xml_doc.root.elements.each('mtn:ttl') do |element|
     element.text="9"
end

File.open(file_path,"w") do |data|
   data<<xml_doc
 end