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();  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章