By GokiSoft.com| 09:53 28/09/2022|
Java Web + WebService

[Source Code] Phân tích tài liệu XML bằng SAXParser - Web Service - C2010G

#books.xml


<?xml version="1.0" encoding="UTF-8"?>

<books>
	<book>
		<title>Lap Trinh C</title>
		<price>100000</price>
		<factory>Aptech</factory>
		<author>TRAN VAN A</author>
		<sem>1</sem>
	</book>
	<book>
		<title>HTML/CSS/JS</title>
		<price>120000</price>
		<factory>Aptech</factory>
		<author>TRAN VAN A</author>
		<sem>1</sem>
	</book>
	<book>
		<title>AngularJS</title>
		<price>150000</price>
		<factory>Aptech</factory>
		<author>TRAN VAN A</author>
		<sem>1</sem>
	</book>
</books>


#category.xml


<?xml version="1.0" encoding="UTF-8"?>

<categories>
	<category>
		<id>1</id>
		<title>Frontend</title>
		<books>
			<book>
				<title>Lap Trinh C</title>
				<price>100000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
			<book>
				<title>HTML/CSS/JS</title>
				<price>120000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
			<book>
				<title>AngularJS</title>
				<price>150000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
		</books>
	</category>
	<category>
		<id>2</id>
		<title>PHP</title>
		<books>
			<book>
				<title>Lap Trinh C</title>
				<price>100000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
			<book>
				<title>HTML/CSS/JS</title>
				<price>120000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
			<book>
				<title>AngularJS</title>
				<price>150000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
		</books>
	</category>
	<category>
		<id>3</id>
		<title>NoteJS</title>
		<books>
			<book>
				<title>Lap Trinh C</title>
				<price>100000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
			<book>
				<title>HTML/CSS/JS</title>
				<price>120000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
			<book>
				<title>AngularJS</title>
				<price>150000</price>
				<factory>Aptech</factory>
				<author>TRAN VAN A</author>
				<sem>1</sem>
			</book>
		</books>
	</category>
</categories>


#Book.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

/**
 *
 * @author Administrator
 */
public class Book {
    String title, factory, author;
    float price;
    int sem;

    public Book() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getFactory() {
        return factory;
    }

    public void setFactory(String factory) {
        this.factory = factory;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public float getPrice() {
        return price;
    }

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

    public int getSem() {
        return sem;
    }

    public void setSem(int sem) {
        this.sem = sem;
    }

    @Override
    public String toString() {
        return "title=" + title + ", factory=" + factory + ", author=" + author + ", price=" + price + ", sem=" + sem;
    }
    
    public void display() {
        System.out.println(this);
    }
}


#BookHandler.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Administrator
 */
public class BookHandler extends DefaultHandler{
    List<Book> bookList;
    
    Book currBook;
    
    boolean isTitle = false;
    boolean isPrice = false;
    boolean isFactory = false;
    boolean isAuthor = false;
    boolean isSem = false;
    
    public BookHandler() {
        bookList = new ArrayList<>();
    }

    public List<Book> getBookList() {
        return bookList;
    }
    
    @Override
    public void startElement(
          String uri,
          String localName,
          String qName,
          Attributes attributes) throws SAXException {
        if(qName.equalsIgnoreCase("book")) {
            currBook = new Book();
        } else if(qName.equalsIgnoreCase("title")) {
            isTitle = true;
        } else if(qName.equalsIgnoreCase("price")) {
            isPrice = true;
        } else if(qName.equalsIgnoreCase("factory")) {
            isFactory = true;
        } else if(qName.equalsIgnoreCase("author")) {
            isAuthor = true;
        } else if(qName.equalsIgnoreCase("sem")) {
            isSem = true;
        }
    }

    @Override
    public void endElement(String uri,
                         String localName,
                         String qName) throws SAXException {
        if(qName.equalsIgnoreCase("book")) {
            bookList.add(currBook);
            currBook = null;
        } else if(qName.equalsIgnoreCase("title")) {
            isTitle = false;
        } else if(qName.equalsIgnoreCase("price")) {
            isPrice = false;
        } else if(qName.equalsIgnoreCase("factory")) {
            isFactory = false;
        } else if(qName.equalsIgnoreCase("author")) {
            isAuthor = false;
        } else if(qName.equalsIgnoreCase("sem")) {
            isSem = false;
        }
    }

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException {
        String value = new String(chars, start, length);
        
        if(isTitle) {
            currBook.setTitle(value);
        } else if(isPrice) {
            currBook.setPrice(Float.parseFloat(value));
        } else if(isFactory) {
            currBook.setFactory(value);
        } else if(isAuthor) {
            currBook.setAuthor(value);
        } else if(isSem) {
            currBook.setSem(Integer.parseInt(value));
        }
    }
    
    
}


#Category.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

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

/**
 *
 * @author Administrator
 */
public class Category implements IHandler{
    int id;
    String title;
    List<Book> bookList;
    
    //Phan hander sub
    Book currBook;
    
    boolean isTitle = false;
    boolean isPrice = false;
    boolean isFactory = false;
    boolean isAuthor = false;
    boolean isSem = false;
    
    public Category() {
        bookList = new ArrayList<>();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    
    public List<Book> getBookList() {
        return bookList;
    }

    public void setBookList(List<Book> bookList) {
        this.bookList = bookList;
    }
    
    public void display() {
        System.out.println("ID = " + id + ", Title = " + title);
        
        System.out.println("Danh sach Book trong danh muc: ");
        bookList.forEach((book) -> {
            book.display();
        });
    }

    @Override
    public void startElement(String qName) {
        if(qName.equalsIgnoreCase("book")) {
            currBook = new Book();
        } else if(qName.equalsIgnoreCase("title")) {
            isTitle = true;
        } else if(qName.equalsIgnoreCase("price")) {
            isPrice = true;
        } else if(qName.equalsIgnoreCase("factory")) {
            isFactory = true;
        } else if(qName.equalsIgnoreCase("author")) {
            isAuthor = true;
        } else if(qName.equalsIgnoreCase("sem")) {
            isSem = true;
        }
    }

    @Override
    public void endElement(String qName) {
        if(qName.equalsIgnoreCase("book")) {
            bookList.add(currBook);
            currBook = null;
        } else if(qName.equalsIgnoreCase("title")) {
            isTitle = false;
        } else if(qName.equalsIgnoreCase("price")) {
            isPrice = false;
        } else if(qName.equalsIgnoreCase("factory")) {
            isFactory = false;
        } else if(qName.equalsIgnoreCase("author")) {
            isAuthor = false;
        } else if(qName.equalsIgnoreCase("sem")) {
            isSem = false;
        }
    }

    @Override
    public void characters(String value) {
        if(isTitle) {
            currBook.setTitle(value);
        } else if(isPrice) {
            currBook.setPrice(Float.parseFloat(value));
        } else if(isFactory) {
            currBook.setFactory(value);
        } else if(isAuthor) {
            currBook.setAuthor(value);
        } else if(isSem) {
            currBook.setSem(Integer.parseInt(value));
        }
    }
}


#CategoryHandler.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Administrator
 */
public class CategoryHandler extends DefaultHandler{
    List<Category> categoryList;
    
    Category currCat = null;
    
    boolean isId = false;
    boolean isTitle = false;
    boolean isBooks = false;
    
    public CategoryHandler() {
        categoryList = new ArrayList<>();
    }

    public List<Category> getCategoryList() {
        return categoryList;
    }
    
    @Override
    public void startElement(
          String uri,
          String localName,
          String qName,
          Attributes attributes) throws SAXException {
        if(qName.equalsIgnoreCase("category")) {
            currCat = new Category();
        } else if(qName.equalsIgnoreCase("books")) {
            isBooks = true;
        } else {
            if(isBooks) {
                //Day vao thanh phan con
                currCat.startElement(qName);
            } else {
                if(qName.equalsIgnoreCase("id")) {
                    isId = true;
                } else if(qName.equalsIgnoreCase("title")) {
                    isTitle = true;
                }
            }
        }
    }

    @Override
    public void endElement(String uri,
                         String localName,
                         String qName) throws SAXException {
        if(qName.equalsIgnoreCase("category")) {
            categoryList.add(currCat);
            currCat = null;
        } else if(qName.equalsIgnoreCase("books")) {
            isBooks = false;
        } else {
            if(isBooks) {
                //Day vao thanh phan con
                currCat.endElement(qName);
            } else {
                if(qName.equalsIgnoreCase("id")) {
                    isId = false;
                } else if(qName.equalsIgnoreCase("title")) {
                    isTitle = false;
                }
            }
        }
    }

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException {
        String value = new String(chars, start, length);
        
        if(isId) {
            currCat.setId(Integer.parseInt(value));
        } else if(isTitle) {
            currCat.setTitle(value);
        } else if(isBooks) {
            //Di vao nhanh con
            currCat.characters(value);
        }
    }
    
}


#IHandler.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

/**
 *
 * @author Administrator
 */
public interface IHandler {
    void startElement(String qName);
    void endElement(String qName);
    void characters(String value);
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        SAXParserFactory factory = SAXParserFactory.newInstance();
        
        try {
            SAXParser parser = factory.newSAXParser();
            BookHandler handler = new BookHandler();
            
            File file = new File("books.xml");
            
            parser.parse(file, handler);
            
            for (Book book : handler.getBookList()) {
                book.display();
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}


#Test.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gokisoft;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author Administrator
 */
public class Test {
    public static void main(String[] args) {
        // TODO code application logic here
        SAXParserFactory factory = SAXParserFactory.newInstance();
        
        try {
            SAXParser parser = factory.newSAXParser();
            CategoryHandler handler = new CategoryHandler();
            
            File file = new File("category.xml");
            
            parser.parse(file, handler);
            
            for (Category category : handler.getCategoryList()) {
                category.display();
            }
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


Tags:



Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó