Parsing an XML file from a zip file The general step is to extract the zip file first, and then parse the XML directly from the zip file to read the input stream from it to reduce the I/O operation. The following is an example of parsing an XML file from a ZIP file:
The code is as follows |
Copy Code |
/** * Parse XML data from zip file <br/> * @param filePath File Absolute path * @return list<?> * @throws IOException * @throws documentexception * @author Desert */ Public list<record> getdatabyxmlzipfile (String filePath) throws IOException, documentexception{ list<record> recordlist = new arraylist<> (); ZIP file ZipFile zipfile = new ZipFile (FilePath); Traversing the ZipEntry entity of the ZipFile file, that is, the XML file for (enumeration< extends zipentry> entries = Zipfile.entries (); entries.hasmoreelements ();) { ZipEntry zipentry = Entries.nextelement (); Gets the input stream of the zipentry from the ZipFile, that is, the input stream of the XML file InputStream InputStream = Zipfile.getinputstream (zipentry); The following uses DOM4J to parse XML files Saxreader reader = new Saxreader (); Document document = Reader.read (InputStream); Reads all the data child node elements of a datas node in an XML document list<element> elementlist = document.selectnodes ("/datas/data"); XML data format: <data record= "xxxxx" date= "2013-06-15 11:22:33"/> for (Element element:elementlist) { Record record = new record (); The Record property value of the data element Record.setrecord (Element.attributevalue ("Record")); Date property value of the data element Record.setdate (Element.attributevalue ("date")); Record added to Recordlist Recordlist.add (record); } Close the stream Inputstream.close (); } return recordlist; } |
Xml
The code is as follows |
Copy Code |
<?xml version= "1.0" encoding= "UTF-8"?> <datas> <data record= "xxxxx" date= "2013-06-15 11:22:33"/> <data record= "yyyyy" date= "2013-06-16 11:22:33"/> <data record= "zzzzz" date= "2013-06-17 11:22:33"/> </datas> |
Record class:
code is as follows |
copy code |
public class Record { private string id; private string Recor D private String Date; public string getId () { return id; } public void SetId (string ID { this.id = ID; } public String Getrecord () { return record; } public void Setrecord (string Record] { this.record = record; } public String getDate () { return da Te } public void setdate (String date) { this.date = date; } |