danhsachsinhvien.xml
Java XML 2016
<?xml version="1.0" encoding="UTF-8"?>
<danhsachsinhvien>
<sinhvien>
<masv>sv01</masv>
<hoten>sinh vien 1</hoten>
</sinhvien>
<sinhvien>
<masv>sv02</masv>
<hoten>sinh vien 2</hoten>
</sinhvien>
<sinhvien>
<masv>sv03</masv>
<hoten>sinh vien 3</hoten>
</sinhvien>
</danhsachsinhvien>
DemoSAX.java
Java XML 2016
package demosax;
public class DemoSAX {
public static void main(String[] args) {
DanhSachSinhVien dssv = new DanhSachSinhVien();
dssv.hienthi();
}
}
DemoSAX.java
Java XML 2016
package demosax;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class DanhSachSinhVien {
public void hienthi() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse("src\\database\\danhsachsinhvien.xml", new DSSVHandler());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private class DSSVHandler 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("sinhvien")) {
this.dem++;
System.out.println("================");
}
if(qName.equals("masv")){
tagName = qName;
}
if(qName.equals("hoten")){
tagName = qName;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if(tagName.equals("masv")){
System.out.println("Ma sinh vien: "+ (new String(ch, start, length)));
this.tagName="";
}
if(tagName.equals("hoten")){
System.out.println("Ho ten: "+ (new String(ch, start, length)));
this.tagName="";
}
}
@Override
public void endDocument() throws SAXException {
System.out.println("================");
System.out.println("Tong so sinh vien la: " + this.dem);
}
}
}
0 nhận xét:
Post a Comment