1

I want to modify all of the files in a zip archive of XML files. When I tried to do this though, it tells me that the file doesn't exist. If I comment out the replace call though this works. What am I doing wrong?

   Zip::ZipFile.open(temp_file.path) do |zipfile|
      for i in 0..(zipfile.entries.count - 1)
        entry = zipfile.entries[i]
        if entry.name
          if entry.name.split("/").last == "patient_manifest.txt"
            next
          end
        end
        next if entry.directory?
        data = zipfile.read(entry.name)


        doc = Nokogiri::XML(data)
        doc.root.add_namespace_definition('cda', 'urn:hl7-org:v3')
        doc.root.add_namespace_definition('sdtc', 'urn:hl7-org:sdtc')
        patient_role_element = doc.at_xpath('/cda:ClinicalDocument/cda:recordTarget/cda:patientRole')
        patient_element = patient_role_element.at_xpath('./cda:patient')
        first = patient_element.at_xpath('cda:name/cda:given').text
        last = patient_element.at_xpath('cda:name/cda:family').text

        id_node = patient_role_element.at_xpath('./cda:id')
        id_node['extension'] = id_node['extension'] + first + last
        xml_file = Tempfile.new('foo')
        begin
          xml_file.write(doc.to_xml)
          zipfile.replace(entry, xml_file.path)
        ensure
          xml_file.close
          xml_file.unlink   # deletes the temp file
        end
      end
    end
Xodarap
  • 11,581
  • 11
  • 56
  • 94
  • It looks like if `zipfile.replace` fails you could have a corrupted archive. I'd recommend expanding the archive to disk first, then iterating over the files, modifying them and writing them back, then recompressing them back into their archive. – the Tin Man Oct 31 '14 at 00:39

0 Answers0