10 November 2016

Read XML Using SAX in Java

Đọc XML với SAX
products.xml
Java XML 2016
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<products>
    <product id="p1">
        <name>Name 1</name>
        <price>20</price>
    </product>
    <product id="p2">
        <name>Name 2</name>
        <price>26</price>
    </product>
    
</products>
ProductSAX.java
Java XML 2016
package dom;

import java.util.logging.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ProductSAX {

    public void Display() {
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            sp.parse("src\\data\\products.xml", new ProductHandler());

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

class ProductHandler extends DefaultHandler {

    private int count = 0;
    private String tagName = "";

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //Lấy giá trị của name và price
        if (this.tagName.equals("name")) {
            System.out.println("name: " + (new String(ch, start, length)));
        }
        if (this.tagName.equals("price")) {
            System.out.println("Price: " + (new String(ch, start, length)));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        //Reset tagname
        this.tagName = "";
        if (qName.equals("product")) {
            System.out.println("========================");
        }
    }

    @Override
    public void endDocument() throws SAXException {
        //Đếm sô sản phẩm
        System.out.println("Number of Product: " + this.count);
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //Lấy giá trị của id
        this.tagName = qName;
        if (qName.equals("product")) {
            this.count++;
        }
        if (attributes.getLength() > 0) {
            System.out.println("Id: " + attributes.getValue(0));
        }
    }

}
Main.java
Java XML 2016
package dom;

public class Main {
    public static void main(String[] args) {
        ProductSAX px = new ProductSAX();
        px.Display();
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang