日常小结-SAX解析xml

前端之家收集整理的这篇文章主要介绍了日常小结-SAX解析xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

SAX可用在解析的过程中处理xml而不需要等到整个文件都存入内存在进行解析:

SAX解析

SAX采用事件处理的方式解析XML文件,利用SAX解析XML文件,涉及两个部分,解析器和事件处理器。

  • 解析器可用使用JAXP的API创建,创建出SAX解析器后,就可以指定解析器去解析某个xml文档。
  • 解析器采用sax方式在解析某个xml文档时,它只要解析到xml文档的一个组成部分,都会调用事件处理器的一个方法,解析器在调用事件处理器的方法时,会把当前解析到的xml文件内容作为方法的参数传递给事件处理器。
  • 事件处理器由程序员编写,程序员通过事件处理器中方法的参数,就可以很轻松的得到sax解析器解析到的数据,从而决定对数据进行处理

阅读ContentHandler API文档,常用方法
- startElement
- endElement
- characters


例子:

<?xml version="1.0" encoding="UTF-8"?>
<书架>
    <>
        <书名 name="xxxxx">java教程</书名>
        <作者>张孝祥</作者>
        <售价>109元</售价>
        <售价>39.00元</售价>
    </>
    <>
        <书名>javaScript教程</书名>
        <作者>张孝祥</作者>
        <售价>28元</售价>
    </>
</书架>

下面程序用于提取所有标签

package demo;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;


import javax.xml.parsers.SAXParserFactory;

import jdk.internal.org.xml.sax.Attributes;
import jdk.internal.org.xml.sax.ContentHandler;
import jdk.internal.org.xml.sax.Locator;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class Demo1 {

    /* * sax 解析xml文档 */

    public static void main(String [] args) throws ParserConfigurationException,SAXException,IOException{
        //1.创建解析工厂(抽象工厂)
        SAXParserFactory factory = SAXParserFactory.newInstance();

        //2.得到解析器
        SAXParser sp = factory.newSAXParser();

        //3.得到读取器
        XMLReader reader = sp.getXMLReader();

        //4.设置内容处理器
        reader.setContentHandler(  new ListHandler());

        //5.读取xml文档内容
        reader.parse("src/book.xml");
    }

}


//得到xml文档所有内容
class ListHandler implements  org.xml.sax.ContentHandler
{

    public void characters(char[] arg0,int arg1,int arg2) {
        // TODO Auto-generated method stub
        System.out.println(new String(arg0,arg1,arg2));
    }

    public void endDocument() {
        // TODO Auto-generated method stub

    }

    public void endElement(String arg0,String arg1,String arg2) {
        // TODO Auto-generated method stub
        System.out.println("<"+arg2+">");
    }

    public void endPrefixMapping(String arg0) {
        // TODO Auto-generated method stub

    }

    public void ignorableWhitespace(char[] arg0,int arg2) {
        // TODO Auto-generated method stub

    }

    public void processingInstruction(String arg0,String arg1) {
        // TODO Auto-generated method stub

    }

    public void setDocumentLocator(Locator arg0) {
        // TODO Auto-generated method stub

    }

    public void skippedEntity(String arg0) {
        // TODO Auto-generated method stub

    }

    public void startDocument() {
        // TODO Auto-generated method stub

    }

    public void startElement(String arg0,String arg2,Attributes arg3) throws jdk.internal.org.xml.sax.SAXException {
        // TODO Auto-generated method stub
        System.out.println("<"+arg2+">");

        for (int i = 0; arg3!=null && i < arg3.getLength(); i++) {
            String attName = arg3.getQName(i);
            String attValue = arg3.getValue(i);
            System.out.println(attName+"="+attValue);

        }
    }

    public void startPrefixMapping(String arg0,String arg1) {
        // TODO Auto-generated method stub

    }

    public void setDocumentLocator(org.xml.sax.Locator locator) {
        // TODO Auto-generated method stub

    }

    public void startElement(String uri,String localName,String qName,org.xml.sax.Attributes atts) throws SAXException {
        // TODO Auto-generated method stub

    }

}

下列程序用于提取特定标签

package demo;

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class Demo2 {

    /* * sax 解析xml文档 */

    public static void main(String [] args) throws ParserConfigurationException,IOException{
        //1.创建解析工厂(抽象工厂)
        SAXParserFactory factory = SAXParserFactory.newInstance();

        //2.得到解析器
        SAXParser sp = factory.newSAXParser();

        //3.得到读取器
        XMLReader reader = sp.getXMLReader();

        //4.设置内容处理器
        reader.setContentHandler(  new TagValueHandler());

        //5.读取xml文档内容
        reader.parse("src/book.xml");
    }

}

//或者指定标签的值
class TagValueHandler extends DefaultHandler{

    private String currenTage;//当前解析到的标签
    @Override
    public void startElement(String uri,Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        currenTage = qName;

    }

    @Override
    public void characters(char[] ch,int start,int length)
            throws SAXException {
        // TODO Auto-generated method stub
        if("作者".equals(currenTage)){
            System.out.println(new String(ch,start,length));
        }
    }

    @Override
    public void endElement(String uri,String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        currenTage = null;
    }
}

下列代码用于将xml解析后封装到bean的list中:

package demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;


public class Demo3 {

    /* * sax 解析xml文档 */

    public static void main(String [] args) throws ParserConfigurationException,IOException{
        //1.创建解析工厂(抽象工厂)
        SAXParserFactory factory = SAXParserFactory.newInstance();

        //2.得到解析器
        SAXParser sp = factory.newSAXParser();

        //3.得到读取器
        XMLReader reader = sp.getXMLReader();

        //4.设置内容处理器
        BeanListHandler handler = new BeanListHandler();
        reader.setContentHandler( handler );

        //5.读取xml文档内容
        reader.parse("src/book.xml");
        List list = handler.getBooks();
        System.out.println(list);
    }

}


class BeanListHandler extends DefaultHandler{

    private List list = new ArrayList();
    private String currentTag;
    private Book book;

    @Override
    public void startElement(String uri,Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        currentTag = qName;
        if("书".equals(currentTag)){
            book = new Book();
        }
    }

    @Override
    public void characters(char[] ch,int length)
            throws SAXException {
        // TODO Auto-generated method stub
        if("书名".equals(currentTag)){
            String name = new String(ch,length);
            book.setName(name);
        }
        if("作者".equals(currentTag)){
            String author = new String(ch,length);
            book.setAuthor(author);
        }
        if("售价".equals(currentTag)){
            String price = new String(ch,length);
            book.setPrice(price);
        }
    }

    @Override
    public void endElement(String uri,String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        if("书".equals(qName)){
            list.add(book);
            book = null;
        }
        currentTag = null;
    }

    public List getBooks() {
        return list;
    }




}

下列代码用于提供bean类

package demo;

public class Book {
    private String name;
    private String author;
    private String price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }


}
原文链接:https://www.f2er.com/xml/295073.html

猜你在找的XML相关文章