java解析xml

目前在Java中用於解析XML的技術很多,主流的有DOMSAXJDOMDOM4j,下文主要介紹這4種解析XML文檔技術的使用、優缺點及性能測試。
 
-------------------------------------------
 
下面你首先說DOMSAX
一、用Java解析XML文檔,最常用的有兩種方法:使用基於事件的XML簡單API(Simple API for XML)稱爲SAX和基於樹和節點的文檔對象模型(Document Object Module)稱爲DOM。Sun公司提供了Java API for XML Parsing(JAXP)接口來使用SAX和DOM,通過JAXP,我們可以使用任何與JAXP兼容的XML解析器。
二、JAXP接口包含了三個包:
(1)       org.w3c.dom  W3C推薦的用於XML標準規劃文檔對象模型的接口。
(2)       org.xml.sax   用於對XML進行語法分析的事件驅動的XML簡單API(SAX)
(3)       javax.xml.parsers解析器工廠工具,程序員獲得並配置特殊的特殊語法分析器。
三、關於使用DOM、SAX編程不要其它的依賴包,因爲JDK裏自帶的JDK裏含有的上面提到的org.w3c.dom、org.xml.sax 和javax.xml.parsers包就可以滿意條件了。
四、使用DOM解析XML文檔
首先是要讀取的XML文件結構:後文代碼中有使用到text.xml(該文檔放在src路徑下,既編譯後在classes路徑下),都是指該xml文檔。
讀取XML文件位置可以使用文件的絕對地址:document = saxReader.read(new File("F:\\手冊\\物流xml\\發貨撤單\\調撥單.xml"));
複製代碼
<?xml version="1.0" encoding="UTF-8"?>  
<university name="pku">  
    <college name="c1">  
        <class name="class1">  
            <student name="stu1" sex='male' age="21" />  
            <student name="stu2" sex='female' age="20" />  
            <student name="stu3" sex='female' age="20" />  
        </class>  
        <class name="class2">  
            <student name="stu4" sex='male' age="19" />  
            <student name="stu5" sex='female' age="20" />  
            <student name="stu6" sex='female' age="21" />  
        </class>  
    </college>  
    <college name="c2">  
        <class name="class3">  
            <student name="stu7" sex='male' age="20" />  
        </class>  
    </college>  
    <college name="c3">  
    </college>  
</university>  
複製代碼

 使用DOM解析,

該代碼只要稍做修改,即可變得更加簡潔,無需一直寫if來判斷是否有子節點。
複製代碼
package test.xml;   
  
import java.io.File;   
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.io.InputStream;   
  
import javax.xml.parsers.DocumentBuilder;   
import javax.xml.parsers.DocumentBuilderFactory;   
import javax.xml.parsers.ParserConfigurationException;   
import javax.xml.transform.Transformer;   
import javax.xml.transform.TransformerConfigurationException;   
import javax.xml.transform.TransformerException;   
import javax.xml.transform.TransformerFactory;   
import javax.xml.transform.dom.DOMSource;   
import javax.xml.transform.stream.StreamResult;   
  
import org.w3c.dom.Document;   
import org.w3c.dom.Element;   
import org.w3c.dom.Node;   
import org.w3c.dom.NodeList;   
import org.w3c.dom.Text;   
import org.xml.sax.SAXException;   
  
/**  
 * dom讀寫xml  
 * @author whwang  
 */  
public class TestDom {   
       
    public static void main(String[] args) {   
        read();   
        //write();   
    }   
       
    public static void read() {   
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
        try {   
            DocumentBuilder builder = dbf.newDocumentBuilder();   
            InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");   
            Document doc = builder.parse(in);   
            // root <university>   
            Element root = doc.getDocumentElement();   
            if (root == null) return;   
            System.err.println(root.getAttribute("name"));   
            // all college node   
            NodeList collegeNodes = root.getChildNodes();   
            if (collegeNodes == null) return;   
            for(int i = 0; i < collegeNodes.getLength(); i++) {   
                Node college = collegeNodes.item(i);   
                if (college != null && college.getNodeType() == Node.ELEMENT_NODE) {   
                    System.err.println("\t" + college.getAttributes().getNamedItem("name").getNodeValue());   
                    // all class node   
                    NodeList classNodes = college.getChildNodes();   
                    if (classNodes == null) continue;   
                    for (int j = 0; j < classNodes.getLength(); j++) {   
                        Node clazz = classNodes.item(j);   
                        if (clazz != null && clazz.getNodeType() == Node.ELEMENT_NODE) {   
                            System.err.println("\t\t" + clazz.getAttributes().getNamedItem("name").getNodeValue());   
                            // all student node   
                            NodeList studentNodes = clazz.getChildNodes();   
                            if (studentNodes == null) continue;   
                            for (int k = 0; k < studentNodes.getLength(); k++) {   
                                Node student = studentNodes.item(k);   
                                if (student != null && student.getNodeType() == Node.ELEMENT_NODE) {   
                                    System.err.print("\t\t\t" + student.getAttributes().getNamedItem("name").getNodeValue());   
                                    System.err.print(" " + student.getAttributes().getNamedItem("sex").getNodeValue());   
                                    System.err.println(" " + student.getAttributes().getNamedItem("age").getNodeValue());   
                                }   
                            }   
                        }   
                    }   
                }   
            }   
        } catch (ParserConfigurationException e) {   
            e.printStackTrace();   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (SAXException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
           
    }   
       
    public static void write() {   
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
        try {   
            DocumentBuilder builder = dbf.newDocumentBuilder();   
            InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml");   
            Document doc = builder.parse(in);   
            // root <university>   
            Element root = doc.getDocumentElement();   
            if (root == null) return;   
            // 修改屬性   
            root.setAttribute("name", "tsu");   
            NodeList collegeNodes = root.getChildNodes();   
            if (collegeNodes != null) {   
                for (int i = 0; i <collegeNodes.getLength() - 1; i++) {   
                    // 刪除節點   
                    Node college = collegeNodes.item(i);   
                    if (college.getNodeType() == Node.ELEMENT_NODE) {   
                        String collegeName = college.getAttributes().getNamedItem("name").getNodeValue();   
                        if ("c1".equals(collegeName) || "c2".equals(collegeName)) {   
                            root.removeChild(college);   
                        } else if ("c3".equals(collegeName)) {   
                            Element newChild = doc.createElement("class");   
                            newChild.setAttribute("name", "c4");   
                            college.appendChild(newChild);   
                        }   
                    }   
                }   
            }   
            // 新增節點   
            Element addCollege = doc.createElement("college");   
            addCollege.setAttribute("name", "c5");   
            root.appendChild(addCollege);   
            Text text = doc.createTextNode("text");   
            addCollege.appendChild(text);   
               
            // 將修改後的文檔保存到文件   
            TransformerFactory transFactory = TransformerFactory.newInstance();   
            Transformer transFormer = transFactory.newTransformer();   
            DOMSource domSource = new DOMSource(doc);   
            File file = new File("src/dom-modify.xml");   
            if (file.exists()) {   
                file.delete();   
            }   
            file.createNewFile();   
            FileOutputStream out = new FileOutputStream(file);            
            StreamResult xmlResult = new StreamResult(out);   
            transFormer.transform(domSource, xmlResult);   
            System.out.println(file.getAbsolutePath());   
        } catch (ParserConfigurationException e) {   
            e.printStackTrace();   
        } catch (SAXException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } catch (TransformerConfigurationException e) {   
            e.printStackTrace();   
        } catch (TransformerException e) {   
            e.printStackTrace();   
        }   
    }   
}  

實現多個不同的JSReport導出文件打包後下載

代碼實現那最基本的實現 沒有重構也沒有整理成方法 主要是自己記錄下思路 

 

說下思路要實現JSReport打包下載

1.需要將JSReport輸出到文件中保存起來

2.將文件輸出到zip流程中實現下載。

複製代碼
public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

//創建數據Map rs = new HashMap(); rs.put("title", "標題");  List list = new ArrayList(); list.add(rs); //表報數據源

JRDataSource ds = new JRMapCollectionDataSource(list);  //報表文件地址 String reportPath = "D:\jkd.jasper"; // 報表參數 Map params = new HashMap(); //報表 JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath,params, ds); //打印列表(一次可以打印多個類型報表) List jasperPrintList = new ArrayList(); jasperPrintList.add(doPrintJkd(ds));  //將表報保存到文件 File[] files = new File[2];    files[0]= new File("文件1.xls"); FileOutputStream fos1= new FileOutputStream(files[0]);JRXlsExporter exporter = new JRXlsExporter();  exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,jasperPrintList); //將表報寫入文件 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,fos1);   files[1]= new File("文件2.doc"); FileOutputStream fos2= new FileOutputStream(files[2]); JRXlsExporter exporter = new JRXlsExporter();  exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,jasperPrintList); //將第二份表報寫入文件 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,fos2); //創建zip輸出流

response.setHeader("Content-Disposition","attachment;filename=xxx.zip");
response.setContentType("APPLICATION/OCTET-STREAM"); //將輸出流設定爲 response ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());  //將文件放入Zip流 for (File f:files) {     zos.putNextEntry(new ZipEntry(f.getName()));      FileInputStream fis = new FileInputStream(f);          byte[] buffer = new byte[1024];      int r = 0;      while ((r = fis.read(buffer)) != -1) {           zos.write(buffer, 0, r);          }       fis.close();   } zos.flush(); zos.close();  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章