11 November 2016

XML SAX: Đọc RSS trên http://vnexpress.net/rss bằng XML

DemoSAX.java
Java XML 2016
package demosax;

public class DemoSAX {

    public static void main(String[] args) {
        RSS dssv = new RSS();
        dssv.hienthi();
    }

}
RSS.java
Java XML 2016
package demosax;

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class RSS {

    public void hienthi() {
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            sp.parse("http://vnexpress.net/rss/tin-moi-nhat.rss", new RSSHandler());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private class RSSHandler extends DefaultHandler {

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

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (qName.equals("item")) {
                this.dem++;
                System.out.println("==========================");
            }
            if (qName.equals("title")) {
                tagName = qName;
            }
            if (qName.equals("description")) {
                tagName = qName;
            }

        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (tagName.equals("title")) {
                System.out.println("Item: " + (new String(ch, start, length)));
                this.tagName = "";
            }
            if (tagName.equals("description")) {
                System.out.println("HTML: " + (new String(ch, start, length)));
                this.tagName = "";
            }
        }

        @Override
        public void startDocument() throws SAXException {
            System.out.println("=========http://vnexpress.net/tin-tuc/thoi-su========");
        }

        @Override
        public void endDocument() throws SAXException {
            System.out.println("Tong so item la: " + this.dem);
        }

    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang