Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write XML files directly to a zip archive?

Tags:

java

xml

zip

jaxb

What is the proper way to write a list of XML files using JAXB directly to a zip archive without using a 3rd party library.

Would it be better to just write all the XML files to a directory and then zip?

like image 395
kdgwill Avatar asked Aug 20 '11 03:08

kdgwill


People also ask

How do I save an XML file as a zip file?

❓ How can I convert XML to ZIP? First, you need to add a file for conversion: drag & drop your XML file or click inside the white area for choose a file. Then click the "Convert" button. When XML to ZIP conversion is completed, you can download your ZIP file.

What is zip or XML file?

The .zip extension is the most common archive format utilised across the internet for storing a collection of files and directories in a single compressed file.

Where are XML files stored?

The product XML file location property defines the location where all the product XML configuration files are stored. This property is set by default to the following locations: For 32-bit Windows operating systems—<Installation location>\Program Files\ArcGIS\MaritimeCharting\Desktop<version>\Common.


1 Answers

As others pointed out, you can use the ZipOutputStream class to create a ZIP-file. The trick to put multiple files in a single ZIP-file is to use the ZipEntry descriptors prior to writing (marshalling) the JAXB XML data in the ZipOutputStream. So your code might look similar to this one:


JAXBElement jaxbElement1 = objectFactory.createRoot(rootType);
JAXBElement jaxbElement2 = objectFactory.createRoot(rootType);

ZipOutputStream zos = null; 
try {
  zos = new ZipOutputStream(new FileOutputStream("xml-file.zip"));
  // add zip-entry descriptor
  ZipEntry ze1 = new ZipEntry("xml-file-1.xml");
  zos.putNextEntry(ze1);
  // add zip-entry data
  marshaller.marshal(jaxbElement1, zos);
  ZipEntry ze2 = new ZipEntry("xml-file-2.xml");
  zos.putNextEntry(ze2);
  marshaller.marshal(jaxbElement2, zos);
  zos.flush();
} finally {
  if (zos != null) {
    zos.close();
  }
}
like image 81
Jiri Patera Avatar answered Sep 30 '22 03:09

Jiri Patera