我正在使用rubyzip和nokogiri的组合来编辑.docx文件.我正在使用rubyzip来解压缩.docx文件,然后使用nokogiri来解析和更改word/document.xml文件的正文,但是我最后关闭rubyzip它会破坏文件而我无法打开它或者修理它.我在桌面上解压缩.docx文件并检查word/document.xml文件,并将内容更新为我更改为的内容,但所有其他文件都搞砸了.有人可以帮我解决这个问题吗?这是我的代码:
require 'rubygems'
require 'zip/zip'
require 'nokogiri'
zip = Zip::ZipFile.open("test.docx")
doc = zip.find_entry("word/document.xml")
xml = Nokogiri::XML.parse(doc.get_input_stream)
wt = xml.root.xpath("//w:t", {"w" => "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}).first
wt.content = "New Text"
zip.get_output_stream("word/document.xml") {|f| f << xml.to_s}
zip.close
Run Code Online (Sandbox Code Playgroud)