SAX 解析到文件,缓存到内存

简介: 目的<br>     通过一个小的SAX例子,我们更清晰的理解SAX的工作原理。<br><br>     本文例子主要实现:<br>     1. 将每个Employee信息输出到自己的文件中,文件名是以Employee ID和Employee Name来命名的,注意,观察代码中是如何得到Employee ID和Employee Name;<br>     2. 将每个Employ
目的
    通过一个小的SAX例子,我们更清晰的理解SAX的工作原理。

    本文例子主要实现:
    1. 将每个Employee信息输出到自己的文件中,文件名是以Employee ID和Employee Name来命名的,注意,观察代码中是如何得到Employee ID和Employee Name;
    2. 将每个Employee信息存入到Map中,其中,Map中的每个Value对应一个Employee的Collection,Map中的每个Key对应该Employee的ID。


    package shuai.study.sax.demo;  
      
    import java.io.File;  
    import java.io.IOException;  
    import java.util.Collection;  
    import java.util.HashMap;  
    import java.util.LinkedList;  
    import java.util.Map;  
      
    import javax.xml.parsers.ParserConfigurationException;  
    import javax.xml.parsers.SAXParser;  
    import javax.xml.parsers.SAXParserFactory;  
      
    import org.apache.commons.io.FileUtils;  
    import org.apache.commons.lang3.StringUtils;  
    import org.xml.sax.Attributes;  
    import org.xml.sax.SAXException;  
    import org.xml.sax.helpers.DefaultHandler;  
      
    /** 
     * @author shengshu 
     *  
     */  
    public class SaxHandler extends DefaultHandler {  
        private final static String leafNodeText = "|firstname|;|lastname|;|sex|;|country|;|province|;|city|;|village|;|mobile|;|mail|;|qq|;|postcode|;|profession|";  
      
        private Map<String, Collection<String>> companyMap = null;  
        private Collection<String> employeeCollection = null;  
      
        private String currentValue = null;  
        private String currentCharacters = null;  
      
        private StringBuffer idAndNameStringBuffer = null;  
      
        public SaxHandler(File inputFile) {  
            this.parseDocument(inputFile);  
        }  
      
        private void parseDocument(File inputFile) {  
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();  
      
            try {  
                SAXParser saxParser = saxParserFactory.newSAXParser();  
                saxParser.parse(inputFile, this);  
            } catch (ParserConfigurationException pce) {  
                pce.printStackTrace();  
            } catch (SAXException saxe) {  
                saxe.printStackTrace();  
            } catch (IOException ioe) {  
                ioe.printStackTrace();  
            }  
        }  
      
        @Override  
        public void startDocument() throws SAXException {  
            super.startDocument();  
            this.companyMap = new HashMap<String, Collection<String>>();  
        }  
      
        @Override  
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {  
            if (qName.equalsIgnoreCase("Employee")) {  
                this.employeeCollection = new LinkedList<String>();  
                this.idAndNameStringBuffer = new StringBuffer();  
      
                this.currentValue = attributes.getValue("ID");  
            }  
        }  
      
        @Override  
        public void characters(char[] buffer, int start, int length) {  
            this.currentCharacters = new String(buffer, start, length);  
        }  
      
        @Override  
        public void endElement(String uri, String localName, String qName) throws SAXException {  
            if (StringUtils.containsIgnoreCase(leafNodeText, "|" + qName + "|")) {  
                this.employeeCollection.add(qName + ": " + this.currentCharacters);  
      
                if (qName.equalsIgnoreCase("FirstName")) {  
                    this.idAndNameStringBuffer.append(this.currentCharacters);  
                }  
      
                if (qName.equalsIgnoreCase("LastName")) {  
                    this.idAndNameStringBuffer.append(this.currentCharacters);  
                }  
            }  
      
            if (qName.equalsIgnoreCase("Employee")) {  
                this.companyMap.put(this.currentValue, this.employeeCollection);  
      
                this.idAndNameStringBuffer.append("-").append(this.currentValue);  
      
                this.writeEmployee(employeeCollection, idAndNameStringBuffer.toString());  
            }  
        }  
      
        private void writeEmployee(Collection<String> employeeCollection, String fileName) {  
            String outputFileDirectory = SaxHandler.class.getResource("/file/output/").getPath();  
            String outputFilePath = outputFileDirectory + fileName + ".xml";  
            File outputFile = new File(outputFilePath);  
      
            try {  
                FileUtils.writeLines(outputFile, employeeCollection, false);  
            } catch (IOException ioe) {  
                ioe.printStackTrace();  
            }  
        }  
      
        @Override  
        public void endDocument() throws SAXException {  
            super.endDocument();  
        }  
      
        public Map<String, Collection<String>> getCompanyMap() {  
            return this.companyMap;  
        }  
      
    }  

    package shuai.study.sax.demo;  
      
    import java.io.File;  
    import java.util.Collection;  
    import java.util.Iterator;  
    import java.util.Map;  
    import java.util.Map.Entry;  
      
    /** 
     * @author shengshu 
     *  
     */  
    public class SaxDemo {  
        public static void displayCompany(Map<String, Collection<String>> companyMap) {  
            Iterator<Entry<String, Collection<String>>> companyIterator = companyMap.entrySet().iterator();  
      
            while (companyIterator.hasNext()) {  
                Entry<String, Collection<String>> companyEntry = companyIterator.next();  
      
                String id = companyEntry.getKey();  
                System.out.println("============== Employee ID " + id + " Start ==============");  
      
                Collection<String> employeeCollection = companyEntry.getValue();  
                Iterator<String> employeeIterator = employeeCollection.iterator();  
      
                while (employeeIterator.hasNext()) {  
                    String leafNodeAndValue = employeeIterator.next();  
                    System.out.println(leafNodeAndValue);  
                }  
      
                System.out.println("============== Employee ID " + id + " End ==============");  
            }  
        }  
      
        public static void main(String[] args) {  
            String inputFilePath = SaxDemo.class.getResource("/file/input/company.xml").getPath();  
            File inputFile = new File(inputFilePath);  
      
            SaxHandler saxHandler = new SaxHandler(inputFile);  
      
            Map<String, Collection<String>> companyMap = saxHandler.getCompanyMap();  
      
            SaxDemo.displayCompany(companyMap);  
        }  
    }  

    <?xml version = "1.0" encoding="UTF-8"?>  
      
    <Company>  
        <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>  

相关文章
|
7天前
|
XML JavaScript 前端开发
xml文件使用及解析
xml文件使用及解析
|
21天前
|
算法 Linux C++
【Linux系统编程】解析获取和设置文件信息与权限的Linux系统调用
【Linux系统编程】解析获取和设置文件信息与权限的Linux系统调用
29 0
|
26天前
|
安全 Java 数据库连接
jdbc解析excel文件,批量插入数据至库中
jdbc解析excel文件,批量插入数据至库中
19 0
|
26天前
|
SQL Java 数据库连接
springboot解析txt文件顺便加到数据库中(nohup文件)
springboot解析txt文件顺便加到数据库中(nohup文件)
108 1
|
26天前
|
XML Java 数据格式
使用java解析XML文件的步骤
使用java解析XML文件的步骤
10 0
|
26天前
|
存储 安全 Linux
C++文件格式深度解析:从底层结构到关键特性
C++文件格式深度解析:从底层结构到关键特性
243 3
C++文件格式深度解析:从底层结构到关键特性
|
28天前
|
JavaScript 前端开发 编译器
Cmake 中 compiler_depend.ts 文件:解析和使用 C/C++ 预编译头文件
Cmake 中 compiler_depend.ts 文件:解析和使用 C/C++ 预编译头文件
22 1
|
1月前
|
存储 缓存 算法
深入探究LRU缓存机制:优化内存利用与提升性能
深入探究LRU缓存机制:优化内存利用与提升性能
93 1
|
1月前
|
消息中间件 测试技术 Python
Python使用多线程解析超大日志文件
Python使用多线程解析超大日志文件
20 0
|
1月前
|
存储 JSON JavaScript
Python中读写(解析)JSON文件的深入探究
Python中读写(解析)JSON文件的深入探究
24 0

推荐镜像

更多