SAX解析和简单Java类

  • 这是我看javaweb教学视频时所做的笔记,加以整理后的内容,目的是为了巩固所学知识,如有雷同,不胜荣幸(#^.^#)

使用SAX解析器将xml文件中的数据保存为java程序类

  • 此时的xml文件数据
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<shop>
	<classfiy>
		<type>人文书籍</type>
		<label></lable>
	</classfiy>
	<book>
		<name>新的世界,新的你</name>
		<year>3</year>
		<price>56.6</price>
	</book>
	<book>
		<name>java入门到跑路</name>
		<year>111</year>
		<price>100</price>
	</book>
</shop>
  • 此时xml文件中描述的是一个商品分类(classfiy)人文书籍下的拥有两本书籍数据,<<新的世界,新的你>>,和<<Java从入门到放弃>>.
  • 目的:将xml文件中的classfiy元素中的数据读取出来,并保存为一个普通java类对象,并且在这个对象中还保存有两个book元素中的信息的引用(“表达的不够好,希望理解”)
  • 定义Classify类保存分类信息
package mao.shu.vo;

import java.util.ArrayList;
import java.util.List;

public class Classfiy {
    private String type;
    private String label;
    private List<Book> bookList = new ArrayList<Book>();

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public List<Book> getBookList() {
        return bookList;
    }

    public void setBookList(List<Book> bookList) {
        this.bookList = bookList;
    }

    @Override
    public String toString() {
        return "Classfiy{" +
                "type='" + type + '\'' +
                ", label='" + label + '\'' +
                ", bookList=" + bookList +
                '}';
    }
}

  • 定义Book类,保存书籍信息
package mao.shu.vo;

public class Book {
    private String name;
    private Integer year;
    private Double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getYear() {
        return year;
    }

    public void setYear(Integer year) {
        this.year = year;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", year=" + year +
                ", price=" + price +
                '}';
    }
}

  • 定义BookParser.java类做xml文件的解析器(暂时使用最简单的名称判断方式,不考虑通用性)

  • 定义一个Classfiy类对象引用,用于保存接收到的数据,利用构造方法,在实例化BookParser类对象的时候传入该参数的引用

    • SAX解析器是按照顺序,逐行解析文件,解析到一个元素的开始,就会触发元素开始事件,根据这个特性,我们在每次触发元素开始事件的时候,将当前元素名称保存起来,
    • 覆写DefaultHHandler父类中的"startElement()"方法,保存当前元素名称,
  • 当解析器读到元素内容的时候,会触发字符事件,此时我们可以根据当前元素的名称来判断是此时的字符是否是我们要保存的数据

在这里插入图片描述

  • 覆写character()方法,当触发字符串的时候,判断当前参数,来保存数据.
  • 在"book"元素结束的时候讲book对象保存到链表中
package mao.shu.Parser;

import mao.shu.vo.Book;
import mao.shu.vo.Classfiy;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class BookParser extends DefaultHandler {
    //保存当前解析的元素名称
    private String currentElement;
    //保存读取出来的数据
    private Classfiy classfiy;

    //保存book属性
    private Book temp = null;

    public BookParser(Classfiy classfiy){
        this.classfiy = classfiy;
    }
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        this.currentElement = qName;
        if("book".equals(qName)){
            this.temp = new Book();
        }
    }
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //得到当前元素中的内容,要消除掉空格
        String chStr = new String(ch,start,length).trim();
        if (chStr.length() > 0) {
            if ("type".equals(this.currentElement)) {
                this.classfiy.setType(chStr);
            }
            if ("label".equals(this.currentElement)) {
                this.classfiy.setLabel(chStr);
            }
            if(this.temp != null) {
                switch (this.currentElement) {
                    case "name": {
                        this.temp.setName(chStr);
                        break;
                    }
                    case "year": {
                        this.temp.setYear(Integer.parseInt(chStr));
                        break;
                    }
                    case "price": {
                        this.temp.setPrice(Double.parseDouble(chStr));
                        break;
                    }
                }

            }

        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(this.temp != null&&"book".equals(qName)){
            this.classfiy.getBookList().add(this.temp);
        }
        super.endElement(uri,localName,qName);
    }

    @Override
    public void endDocument() throws SAXException {

    }

    public Classfiy getClassfiy() {
        return classfiy;
    }
}

  • 定义TestBookParser.java类作为客户端调用
package mao.shu.test;

import mao.shu.Parser.BookParser;
import mao.shu.vo.Classfiy;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

public class TestBookParser {
    public static void main(String[] args)throws Exception {
        //创建SAX解析器
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();
        //定义原xml文件
        File xmlFIle = new File("e:"+File.separator+"testWeb"+File.separator+"info.xml");
        Classfiy datas = new Classfiy();
        saxParser.parse(xmlFIle,new BookParser(datas));
        System.out.println(datas);
    }
}

  • 运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43386754/article/details/85640888