欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

XML使用SAX方式解析

程序员文章站 2022-05-29 20:03:50
...
1. XML使用SAX方式解析

SAX的工作原理简单地说就是对文档进行顺序扫描,当扫描到文档(document)开始与结束、元素(element)开始与结束、文档(document)结束等地方时通知事件处理函数,由事件处理函数做相应动作,然后继续同样的扫描,直至文档结束。
优点:消耗资源比较少;适合大文件解析;
缺点:只能读取不能修改;开发复杂;


1.1 使用SAX方式读取XML文件

<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student>
        <name id="001" xx="哈哈">张三</name>
        <sex>男</sex>
        <age>20</age>
    </student>
    <student>
        <name id="002">李四</name>
        <sex>女</sex>
        <age>21</age>
    </student>
</students>


package com.andrew.xml;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAX01 extends DefaultHandler {
    @Override
    public void startDocument() throws SAXException {
        System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    }
    @Override
    public void endDocument() throws SAXException {
        System.out.print("\n 扫描文档结束");
    }
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.print("<");
        System.out.print(qName);
        if (attributes != null) {
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.print(" " + attributes.getQName(i) + "=\"" + attributes.getValue(i) + "\"");
            }
        }
        System.out.print(">");
    }
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.print("</");
        System.out.print(qName);
        System.out.print(">");
    }
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.print(new String(ch, start, length));
    }

    public static void main(String[] args) throws Exception {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse("src/students.xml", new SAX01());
    }
}
运行结果:
<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student>
        <name id="001" xx="哈哈">张三</name>
        <sex>男</sex>
        <age>20</age>
    </student>
    <student>
        <name id="002">李四</name>
        <sex>女</sex>
        <age>21</age>
    </student>
</students>
 扫描文档结束


1.2 使用SAX方式读取XML数据到Bean

<?xml version="1.0" encoding="UTF-8"?>
<students>
    <student id="001">
        <name>张三</name>
        <sex>男</sex>
        <age>20</age>
    </student>
    <student id="002">
        <name>李四</name>
        <sex>女</sex>
        <age>21</age>
    </student>
</students>


package com.andrew.model;
public class Student {
    private String id;
    private String name;
    private String sex;
    private int age;
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
    }
    // getter and setter
}


package com.andrew.xml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.andrew.model.Student;
public class SAX02 extends DefaultHandler {
    private List<Student> students = null;
    private Student student = null;
    private String preTag = null; // 标记上一个节点名称
    @Override
    public void startDocument() throws SAXException {
        System.out.println("开始读取学生信息");
        students = new ArrayList<Student>();
    }
    @Override
    public void endDocument() throws SAXException {
        System.out.println("学生信息读取完毕");
    }
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if ("student".equals(qName)) {
            student = new Student();
            student.setId(attributes.getValue(0));
        }
        preTag = qName;
    }
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ("student".equals(qName)) {
            students.add(student);
            student = null;
        }
        preTag = null;
    }
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (preTag != null) {
            String content = new String(ch, start, length);
            if ("name".equals(preTag)) {
                student.setName(content);
            } else if ("sex".equals(preTag)) {
                student.setSex(content);
            } else if ("age".equals(preTag)) {
                student.setAge(Integer.parseInt(content));
            }
        }
    }
    public static void main(String[] args) throws Exception {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        SAX02 sax02 = new SAX02();
        parser.parse("src/studentsSax.xml", sax02);
        for (Student s : sax02.students) {
            System.out.println(s);
        }
    }
}

运行结果:
开始读取学生信息
学生信息读取完毕
Student [id=001, name=张三, sex=男, age=20]
Student [id=002, name=李四, sex=女, age=21]
相关标签: xml