Sax 解析 XMl

Posted hanshaowu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sax 解析 XMl相关的知识,希望对你有一定的参考价值。

最近工作中遇到了解析xml文件问题,xpath < SAX < spring-oxm

遂记录下来

代码结构:
技术分享图片

 取得所指定节点


 1 package com.example.demo.sax.common;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import com.example.demo.sax.model.User;
 7 import lombok.Builder;
 8 import org.xml.sax.Attributes;
 9 import org.xml.sax.SAXException;
10 import org.xml.sax.helpers.DefaultHandler;
11 
12 public class XmlParseHandler extends DefaultHandler {
13     // xml片段内容
14     private StringBuilder sb = new StringBuilder();
15     // 片段名称
16     private String strTag = "";
17     // 开始时间
18     long starTime;
19     // 结束时间
20     long endTime;
21     // 开始记录
22     private boolean bolStartRecordFlg = false;
23 
24     public XmlParseHandler(String tag) {
25         this.strTag = tag;
26     }
27 
28     /**
29      * 文档解析开始调用
30      */
31     @Override
32     public void startDocument() throws SAXException {
33         starTime = System.currentTimeMillis();
34         System.out.println("开始读取文档:" + starTime);
35     }
36 
37     /**
38      * 文档解析结束后调用
39      */
40     @Override
41     public void endDocument() throws SAXException {
42         endTime = System.currentTimeMillis();
43         System.out.println("结束读取文档:" + endTime);
44         System.out.println("用时:" + (endTime - starTime));
45     }
46 
47 
48     @Override
49     public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
50 
51         if (qName.equals(strTag)) {
52             bolStartRecordFlg = true;
53         }
54         if (bolStartRecordFlg) {
55             sb.append("<" + qName + ">");
56         }
57 
58     }
59 
60     @Override
61     public void endElement(String uri, String localName, String qName) throws SAXException {
62 
63         if (bolStartRecordFlg) {
64             sb.append("</" + qName + ">");
65         }
66         if (qName.equals(strTag)) {
67             bolStartRecordFlg = false;
68             //System.out.println(sb.toString());
69             doSomething(sb.toString());
70             sb.delete(0,sb.length());
71         }
72     }
73 
74     @Override
75     public void characters(char[] ch, int start, int length) throws SAXException {
76         if(bolStartRecordFlg){
77             sb.append(new String(ch,start,length));
78         }
79     }
80 
81     public void doSomething(String strXml){
82 
83     }
84 }

 

考虑替换
package com.example.demo.sax.handler;

import com.example.demo.sax.common.XmlParseHandler;

import java.util.ArrayList;

public class Handler extends XmlParseHandler {
    private ArrayList<String> arrayList ;

    public Handler(ArrayList<String> arrayList, String tag) {
        super(tag);
        this.arrayList = arrayList;
    }

    @Override
    public void doSomething(String strXml) {
        arrayList.add(strXml);
    }
}

测试代码
package com.example.demo.sax;

import com.example.demo.sax.handler.Handler;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;

@Configuration
public class TestSAX {

    private static String file= "D:\\WorkSpace\\sax\\src\\main\\resources\\xml\\users.xml";

    public static void main(String[] args) throws Exception{
        ArrayList<String> arrayList = new ArrayList<String>();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(file,new Handler(arrayList,"user"));
        arrayList.toString();
    }

}

 

这是将来会用到的依赖,先引入进来。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.demo</groupId>
    <artifactId>sax</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>sax</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

经过测试遍历300mb的xml文件,仅仅需要4秒,真的快。。。。。。

 

 









以上是关于Sax 解析 XMl的主要内容,如果未能解决你的问题,请参考以下文章

XML.03-DOM和SAX解析

XML文件解析安卓7——SAX解析

XML文件解析DOM解析和SAX解析

XML解析,SAX解析XML

Android 之XML数据解析—— SAX解析

在BlackBerry中使用SAX解析器解析XML