XML解析与写入(DOM4J)

一,dom4j方式XML文件写入

    public boolean createXML() {
        XMLWriter writer = null;
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");

        Document document = DocumentHelper.createDocument();
        Element tranData = document.addElement("TranData");
        
        Element baseInfo = tranData.addElement("BaseInfo");
        baseInfo.addElement("MakeDate").setText(mMakeDate);
        baseInfo.addElement("MakeTime").setText(mMakeTime);
      
        Element inquireInfo = tranData.addElement("InquireInfo");
        inquireInfo.addElement("NoteDate").setText(mMakeDate);
        inquireInfo.addElement("NoteTime").setText(mMakeTime);
        
        File file = new File("C:\\Users\\Administrator\\Desktop\\commonRecord.xml");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            writer = new XMLWriter(new FileOutputStream(file), format);
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    
二,dom4j方式XML读取

    public boolean ReadXml(){

        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("books.xml"));
        Element root = document.getRootElement();
          
        Iterator it = root.elementIterator();
        while (it.hasNext()) {
            Element element = (Element) it.next();
              
            //未知属性名称情况下
            Iterator attrIt = element.attributeIterator();
            while (attrIt.hasNext()) {
                Attribute a  = (Attribute) attrIt.next();
                System.out.println(a.getValue());
            }
              
            //未知元素名情况下
            Iterator eleIt = element.elementIterator();
            while (eleIt.hasNext()) {
                Element e = (Element) eleIt.next();
                System.out.println(e.getName() + ": " + e.getText());
            }
        }
    }


三,OutputStreamWriter写入

    OutPutStreamWriter out = new OutPutStreamWriter(new FileOutputStream(writerFile),"UTF-8");
    out.write("<?xml version=\"1.0\" encoding=\"GBK\"?>");
    out.write("<BaseInfo>")
    out.write("<MakeDate>2019-04-05</MakeDate>");
    out.write("<MakeDate>\n");
    out.write("</BaseInfo>")
    out.flush();
    out.close();
    
    
四,字符转为xml并解析

    public boolean toStrXml(String reXmlStr) {

        org.dom4j.Document doc = null;
        try {
            doc=(Document) DocumentHelper.parseText(reXmlStr);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootElt = doc.getRootElement();
        
        if (rootElt==null) {
            return false;
        }
        
        String tCompanyCode=rootElt.element("ele1").element("ele2").getText();
    }        

    
五,DocumentBuilderFactory读取字符的方式读取

    public boolean getXMLInfo(String tInqXML) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            StringReader sr = new StringReader(tInqXML);
            InputSource is = new InputSource(sr);
            DocumentBuilder builder = factory.newDocumentBuilder();
            org.w3c.dom.Document mDoc = builder.parse(is);
            org.w3c.dom.Element mElement = mDoc.getDocumentElement();
            this.mMakeDate = mElement.getElementsByTagName("MakeDate").item(0)
                    .getFirstChild()==null?"":mElement.getElementsByTagName("MakeDate")
                            .item(0).getFirstChild().getNodeValue();
            this.mMakeTime = mElement.getElementsByTagName("MakeTime").item(0)
                    .getFirstChild()==null?"":mElement.getElementsByTagName("MakeTime")
                            .item(0).getFirstChild().getNodeValue();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
五,读取续写或新建

    createOrWriteFileList("111", "C:\\Users\\Administrator\\Desktop\\123", "C:\\Users\\Administrator\\Desktop\\Index\\123.xml");

    public static boolean createOrWriteFileList(String applyNo, String batchPath,String xmlPath){
        File Indexfiles = new File(batchPath+"/index");      //文件
        File fileList = new File(batchPath+"/FileList.xml"); //FileList详情文件
        File xmlFile = new File(xmlPath);  //新增xml文件
        
        XMLWriter writer = null;
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        org.dom4j.Document document = null;
        org.dom4j.Element addEle = null;
        
        if(fileList.exists()){
            SAXReader reader = new SAXReader();
            try {
                document = reader.read(fileList);
                org.dom4j.Element root =  document.getRootElement();
                root.element("MakeDate").setText("312");
                root.element("MakeTime").setText("123");
                
                List<org.dom4j.Element> listEles = root.selectNodes("/FileList/LP/FILES");
                org.dom4j.Element filesList = listEles.get(0);
                org.dom4j.Element countEle = filesList.element("FILECOUNT");
                countEle.setText(String.valueOf(Integer.valueOf(countEle.getText())+1));
                
                addEle = filesList.addElement("FILE");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            document = DocumentHelper.createDocument();
            org.dom4j.Element tranData = document.addElement("FileList");
            tranData.addElement("MakeDate").setText("2018-12-26");
            tranData.addElement("MakeTime").setText("12:12:12");
            org.dom4j.Element LP = tranData.addElement("LP");
            org.dom4j.Element files = LP.addElement("FILES");
            if(!Indexfiles.exists()){
                files.addElement("FILECOUNT").setText("0");
            }else{
                File [] fs = Indexfiles.listFiles();
                if(fs == null || fs.length == 0){
                    files.addElement("FILECOUNT").setText("0");
                }else{
                    files.addElement("FILECOUNT").setText(String.valueOf(fs.length));
                    addEle= files.addElement("FILE");
                }
            }
        }
        
        addEle.addElement("CLMNO").setText(applyNo);
        addEle.addElement("FILENAME").setText(xmlFile.getName());
        addEle.addElement("FILEPATH").setText("/"+xmlFile.getParentFile().getName());
        addEle.addElement("FILESIZE").setText(String.valueOf(xmlFile.length()));
        
        try {
            writer = new XMLWriter(new FileOutputStream(fileList), format);
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    
    
六,读取文件内容并转码

    private String readString(String FILE_IN){
        String str="";
        File file=new File(FILE_IN);
        try {
            FileInputStream in=new FileInputStream(file);
            int size=in.available();
            byte[] buffer=new byte[size];
            in.read(buffer);
            in.close();
            str=new String(buffer,"GBK"); //和要求保持一致
        } catch (IOException e) {
            return null;
        }
        return str;
    }

 

上一篇:新文档


下一篇:文本框显示时间