`
threeman
  • 浏览: 10707 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

DOM4j 拆分XML

 
阅读更多
目的

本文例子主要是将XML文件按某个节点拆分。至于DOM4j和SAX之间的区别也非常明显,在此我就不用赘述。我们通过一个实例来理解一下DOM4j的拆分功能。


    package shuai.study.dom4j.demo;  
      
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.FileNotFoundException;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.io.OutputStream;  
    import java.io.UnsupportedEncodingException;  
    import java.util.ArrayList;  
    import java.util.Iterator;  
    import java.util.List;  
      
    import org.apache.commons.io.FileUtils;  
    import org.apache.commons.io.FilenameUtils;  
    import org.apache.commons.io.IOUtils;  
    import org.dom4j.Attribute;  
    import org.dom4j.Document;  
    import org.dom4j.DocumentException;  
    import org.dom4j.DocumentHelper;  
    import org.dom4j.Element;  
    import org.dom4j.io.OutputFormat;  
    import org.dom4j.io.SAXReader;  
    import org.dom4j.io.XMLWriter;  
      
    /** 
     * @author shengshu 
     *  
     */  
    public class Dom4jHandler {  
        private static volatile int pageNumber = -1;  
      
        private Document getDocument(File inputFile) {  
            SAXReader saxReader = new SAXReader();  
            Document document = null;  
      
            try {  
                document = saxReader.read(new FileInputStream(inputFile));  
            } catch (FileNotFoundException | DocumentException e) {  
                e.printStackTrace();  
            }  
      
            return document;  
        }  
      
        private Element getRootElement(Document document) {  
            return document.getRootElement();  
        }  
      
        public List<File> splitXml(File inputFile, String outputFileDirectory, String splitNodeString, int nodeLimitCount) {  
            Document document = this.getDocument(inputFile);  
            Element rootElement = this.getRootElement(document);  
      
            if (document == null || rootElement == null) {  
                throw new NullPointerException();  
            }  
      
            Document fragmentDocument = null;  
      
            List<File> exportFileList = new ArrayList<File>();  
            File exportFile = null;  
      
            Element tempRootElement = null;  
            int splitNodeIndex = 0;  
      
            Iterator<?> iterator = rootElement.elementIterator(splitNodeString);  
            while (iterator.hasNext()) {  
                if (splitNodeIndex == nodeLimitCount || splitNodeIndex == 0) {  
                    if (splitNodeIndex == nodeLimitCount) {  
                        exportFile = this.saveXml(fragmentDocument, this.getOutputFile(outputFileDirectory, inputFile, ++pageNumber));  
      
                        if (exportFile != null) {  
                            exportFileList.add(exportFile);  
                        }  
      
                        splitNodeIndex = 0;  
                    }  
      
                    fragmentDocument = DocumentHelper.createDocument();  
      
                    tempRootElement = fragmentDocument.addElement(rootElement.getName());  
                    tempRootElement.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");  
      
                    List<?> attributeList = rootElement.attributes();  
                    Iterator<?> attributeIterator = attributeList.iterator();  
                    while (attributeIterator.hasNext()) {  
                        Attribute attribute = (Attribute) attributeIterator.next();  
                        tempRootElement.addAttribute(attribute.getName(), attribute.getValue());  
                    }  
                }  
      
                Element splitElement = (Element) iterator.next();  
                tempRootElement.add((Element) splitElement.clone());  
                splitNodeIndex++;  
            }  
      
            if (fragmentDocument != null) {  
                exportFile = this.saveXml(fragmentDocument, this.getOutputFile(outputFileDirectory, inputFile, ++pageNumber));  
      
                if (exportFile != null) {  
                    exportFileList.add(exportFile);  
                }  
            }  
      
            return exportFileList;  
        }  
      
        private File saveXml(Document document, File outputFile) {  
            OutputStream fileOutputStream = null;  
            XMLWriter xmlWriter = null;  
      
            OutputFormat format = OutputFormat.createPrettyPrint();  
      
            try {  
                FileUtils.touch(outputFile);  
                fileOutputStream = new FileOutputStream(outputFile);  
      
                xmlWriter = new XMLWriter(fileOutputStream, format);  
                xmlWriter.write(document);  
                xmlWriter.flush();  
            } catch (FileNotFoundException fnfe) {  
                fnfe.printStackTrace();  
            } catch (UnsupportedEncodingException uee) {  
                uee.printStackTrace();  
            } catch (IOException ioe) {  
                ioe.printStackTrace();  
            } finally {  
                if (xmlWriter != null) {  
                    try {  
                        xmlWriter.close();  
                    } catch (IOException ioe) {  
                        ioe.printStackTrace();  
                    }  
                }  
      
                IOUtils.closeQuietly(fileOutputStream);  
            }  
      
            return outputFile;  
        }  
      
        private File getOutputFile(String outputFileDirectory, File inputFile, int pageNumber) {  
            String fileName = inputFile.getName();  
            String fileBaseName = FilenameUtils.getBaseName(fileName);  
            String fileNameExtension = FilenameUtils.getExtension(fileName);  
      
            String outputFilePath = outputFileDirectory + File.separator + fileBaseName + "-" + this.pagingFormat(pageNumber) + "." + fileNameExtension;  
            File outputFile = new File(outputFilePath);  
      
            return outputFile;  
        }  
      
        private synchronized String pagingFormat(int pageNumber) {  
            String pageNumberStr = "P00";  
      
            if (pageNumber < 0) {  
                throw new NumberFormatException("The page number should not be negative");  
            }  
      
            if (pageNumber < 10) {  
                pageNumberStr = String.format("P0%d", pageNumber);  
            } else {  
                pageNumberStr = String.format("P%d", pageNumber);  
            }  
      
            return pageNumberStr;  
        }  
    }  

    package shuai.study.dom4j.demo;  
      
    import java.io.File;  
      
    /** 
     * @author shengshu 
     *  
     */  
    public class Dom4jDemo {  
        public static void main(String[] args) {  
            String inputFilePath = Dom4jHandler.class.getResource("/file/input/company.xml").getPath();  
            File inputFile = new File(inputFilePath);  
      
            String outputFileDirectory = Dom4jHandler.class.getResource("/file/output").getPath();  
      
            String splitNodeString = "Employee";  
            int nodeLimitCount = 1;  
      
            Dom4jHandler dom4jHandler = new Dom4jHandler();  
            dom4jHandler.splitXml(inputFile, outputFileDirectory, splitNodeString, nodeLimitCount);  
        }  
    }  

    <?xml version = "1.0" encoding="UTF-8"?>  
      
    <Company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:noNamespaceSchemaLocation="CompanyFileFormat.xsd">  
        <Message>XXX Company Employee Message</Message>  
      
        <Employee ID="37">  
            <Name>  
                <FirstName>Zhou</FirstName>  
                <LastName>Shengshuai</LastName>  
            </Name>  
      
            <Sex>Male</Sex>  
      
            <Address>  
                <Country>China</Country>  
                <Province>ShanDong</Province>  
                <City>LinYi</City>  
                <Village>FengHuangYu</Village>  
      
                <Contact>  
                    <Mobile>18108***778</Mobile>  
                    <Mail>zhoushengshuai2007@163.com</Mail>  
                    <QQ>254392398</QQ>  
                    <Postcode>276422</Postcode>  
                </Contact>  
            </Address>  
      
            <Profession>Software</Profession>  
        </Employee>  
      
        <Employee ID="66">  
            <Name>  
                <FirstName>Wang</FirstName>  
                <LastName>Eric</LastName>  
            </Name>  
      
            <Sex>Male</Sex>  
      
            <Address>  
                <Country>China</Country>  
                <Province>HeBei</Province>  
                <City>QinHuangDao</City>  
                <Village>hhh</Village>  
      
                <Contact>  
                    <Mobile>150*****955</Mobile>  
                    <Mail>eric@163.com</Mail>  
                    <QQ>666666666</QQ>  
                    <Postcode>111666</Postcode>  
                </Contact>  
            </Address>  
      
            <Profession>Software</Profession>  
        </Employee>  
      
        <Employee ID="99">  
            <Name>  
                <FirstName>Shi</FirstName>  
                <LastName>Stone</LastName>  
            </Name>  
      
            <Sex>Male</Sex>  
      
            <Address>  
                <Country>China</Country>  
                <Province>HeNan</Province>  
                <City>PingDingShan</City>  
                <Village>nnn</Village>  
      
                <Contact>  
                    <Mobile>186*****015</Mobile>  
                    <Mail>stone@163.com</Mail>  
                    <QQ>999999999</QQ>  
                    <Postcode>111999</Postcode>  
                </Contact>  
            </Address>  
      
            <Profession>Software</Profession>  
        </Employee>  
    </Company>  


分享到:
评论

相关推荐

    多文件上传 加水印 生成缩略图 压缩图片 生成xml文档 拆分xml文档 ASP.NET

    本项目的功能是上传文件 处理图片(加水印,生成缩略图,压缩图片) 生成XML文档 拆分XML文档

    使用StAX进行高效的XML处理中文版

    使用StAX进行高效的XML处理中文版 强烈推荐

    JavaScript王者归来part.1 总数2

     12.8.2 如何使用XML DOM--一个利用XML实现多级关联下拉选择框的例子   12.9 总结   第13章 事件处理  13.1 什么是事件   13.1.1 消息与事件响应   13.1.2 浏览器的事件驱动机制   13.2 基本事件处理  ...

    精通JavaScript+jQuery Part1

     13.6 实例四:图片淡入淡出   13.7 实例五:CSS实现PPT幻灯片   13.8 实例六:灯光效果   13.9 实例七:舞台灯光   13.10 实例八:探照灯   13.11 实例九:鼠标文字跟随   第14章 CSS与XML的...

    Java语言基础下载

    DOM4J解析实例 412 JDOM解析实例 413 JAVA操纵XML 实例讲解 414 通过JAVA写数据到XML里面 415 内容总结 418 独立实践 418 第二十三章:HTML基础 419 学习目标 419 知识要点 420 HTML元素 420 标签属性 420 HTML基本...

    超全的Web渗透自我学习资料合集(64篇).zip

    web渗透: XML注入攻击 web渗透: XXE外部实体注入 web渗透: 服务器端包含注入(SSI注入) web渗透: XPath注入 web渗透: 命令注入 web渗透: HTTP响应头拆分漏洞 web渗透: LDAP注入 web渗透: ORM注入 web渗透: Json劫持...

    jQuery攻略.pdf

     第1章 jQuery基础知识 1 1.1 jQuery的安装 1 1.2 选择DOM节点 2 1.3 延迟JavaScript的执行 3 1.4 把CSS应用到元素上 3 1.5 选择一系列非标准的HTML元素 4 1.6 计数DOM节点和显示其文本 5 1.7 获得一个元素的HTML...

    web渗透系列教学下载共64份.zip

    web渗透--23--XML注入攻击.pdf web渗透--24--XXE外部实体注入.pdf web渗透--25--服务器端包含注入(SSI注入).pdf web渗透--26--XPath注入.pdf web渗透--27--命令注入.pdf web渗透--28--HTTP响应头拆分漏洞.pdf web...

    JTBC网站内容管理系统jenfy美化版

    本系统使用ASP环境,使用本系统的空间必须具备Scripting.FileSystemObject,Adodb.Stream,Microsoft.XMLDOM,Scripting.Dictionary等组件支持(均为IIS默认具备的组件无需安装),一些功能可以选择使用诸如Persits....

Global site tag (gtag.js) - Google Analytics