Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 24 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
24
Dung lượng
873,74 KB
Nội dung
Processing XML Using JavaLab01 Introduction to JAXP Simple API for XML (SAX) Mục tiêu - Sửdụng SAX duyệt file XML - Cách cài đặt Parser (SAXParserFactory, SAXParser) -Sử dụng Parsing Content cách kế thừa ContentHandler, DefaultHandler -Sử dụng XMLReader để đăng ký phân tích file XML -Sử dụng ErrorHandler -Sử dụng FilterHandler Phần I Bài tập step by step Bài 1.1 Phân tích file Employees.xml SAX: Input: Employees.xml IT Research Department @BKAP 2015 Trang / 24 Architecting Applications for the Web Output: In hình theo SAX Parser Step 1: Tạo project java netbean File New Project Java Java Application Project Name: Đặt tên project INTXML Sau tạo ta Project có cấu trúc sau: Step 2: Tạo file Employees.xml Project New XML XML Document IT Research Department @BKAP 2015 Trang / 24 Processing XML Using Java IT Research Department @BKAP 2015 Trang / 24 Architecting Applications for the Web File Employees.xml sau tạo thành Tạo nội dung cho Employees.xml Allen Smith Alaska John Davis IT Research Department @BKAP 2015 Trang / 24 Processing XML Using Java California Bob Thomson Kansas Step 3: Tạo lớp xử lý nội dungXML – Content Handler Intxml New Java Java Class SaxHandler.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 intxml; IT Research Department @BKAP 2015 Trang / 24 Architecting Applications for the Web import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * * @author DELL */ public class SaxHandler implements ContentHandler{ //Các cờ đánh dấu in characters boolean foundfirstname; boolean foundlastname; boolean foundlocation; //Start Document @Override public void startDocument() throws SAXException { System.out.println("Start document"); } //End Document @Override public void endDocument() throws SAXException { System.out.println("End document"); } //Start Element @Override public void startElement(String uri, String name, String qname, Attributes attributes) throws SAXException { System.out.println("Start element: "+qname); //In attributes element employee if (qname.equals("employee")) { int atts = attributes.getLength(); for (int i = 0; i < atts; i++) { String atrName = attributes.getQName(i); String atrValue = attributes.getValue(i); System.out.println("Attributes: "+atrName+" "+atrValue); } } //Dựng cờ element cần in if (qname.equals("firstname")) { foundfirstname = true; IT Research Department @BKAP 2015 Trang / 24 Processing XML Using Java } if (qname.equals("lastname")) { foundlastname = true; } if (qname.equals("location")) { foundlocation = true; } } //End Element @Override public void endElement(String uri, String name, String qname) throws SAXException { System.out.println("End element: "+qname); } //In Characters với cờ dựng @Override public void characters(char ch[], int start, int length) throws SAXException { if (foundfirstname) { System.out.println("Characters: "+new String(ch,start,length)); foundfirstname=false; } if (foundlastname) { System.out.println("Characters: "+new String(ch,start,length)); foundlastname=false; } if (foundlocation) { System.out.println("Characters: "+new String(ch,start,length)); foundlocation=false; } } @Override public void setDocumentLocator(Locator locator) { } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { IT Research Department @BKAP 2015 Trang / 24 Architecting Applications for the Web } @Override public void endPrefixMapping(String prefix) throws SAXException { } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } @Override public void processingInstruction(String target, String data) throws SAXException { } @Override public void skippedEntity(String name) throws SAXException { } } Lưu ý: implements ContentHandler phải implement tất abstract methods extends DefaultHandler dùng methods cần sửdụng Step 4: Triển khai hàm main chương trình INTXML.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 intxml; IT Research Department @BKAP 2015 Trang / 24 Processing XML Using Java import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * * @author DELL */ public class INTXML { /** * @param args the command line arguments */ public static void main(String[] args) { try { //Tạo SaxHandler xử lý nội dung SaxHandler sax = new SaxHandler(); //Tạo SAX ParserFactory SAXParserFactory parserFactory = SAXParserFactory.newInstance(); //Tạo SAX Parser Factory khai báo SAXParser parser = parserFactory.newSAXParser(); //Khai báo XML Reader dựa SAXParser object XMLReader xmlReader = parser.getXMLReader(); //Xác định đối tượng chịu trách nhiệm xử lý nội dungXML xmlReader.setContentHandler(sax); //Tiến hành phân tích liệu nguồn cung cấp file XML xmlReader.parse(new InputSource("Employees.xml")); } catch (Exception e) { e.printStackTrace(); } } } Project sau hoàn thành IT Research Department @BKAP 2015 Trang / 24 Architecting Applications for the Web Step 5: Build Run ứng dụng Bài 1.2 Phát triển tiếp 1.1 SửdụngXML locator để vị trí current parser phân tích Sửdụng Instruc tions để đọc thị chương trình khác có định dạng: Thông báo lỗi file XML sai cấu trúc Step 1: SửdụngXML locator để vị trí current parser SaxHandler.java IT Research Department @BKAP 2015 Trang 10 / 24 Processing XML Using 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 intxml; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * * @author DELL */ public class SaxHandler implements ContentHandler{ //Khai báo biến locator private Locator locator; //Các cờ đánh dấu in characters boolean foundfirstname; boolean foundlastname; boolean foundlocation; //Start Document @Override public void startDocument() throws SAXException { System.out.println("Start document"); } //End Document @Override public void endDocument() throws SAXException { System.out.println("End document"); } //Start Element @Override public void startElement(String uri, String name, String qname, Attributes attributes) throws SAXException { System.out.println("Start element: "+qname); //In location cua element dang duyet if (locator!=null) { IT Research Department @BKAP 2015 Trang 11 / 24 Architecting Applications for the Web System.out.println("LOCATOR XML-document name: "+locator.getSystemId()+", column"+locator.getColumnNumber()+", line"+locator.getLineNumber()); } //In attributes element employee if (qname.equals("employee")) { int atts = attributes.getLength(); for (int i = 0; i < atts; i++) { String atrName = attributes.getQName(i); String atrValue = attributes.getValue(i); System.out.println("Attributes: "+atrName+" "+atrValue); } } //Dựng cờ element cần in if (qname.equals("firstname")) { foundfirstname = true; } if (qname.equals("lastname")) { foundlastname = true; } if (qname.equals("location")) { foundlocation = true; } } //End Element @Override public void endElement(String uri, String name, String qname) throws SAXException { System.out.println("End element: "+qname); } //In Characters với cờ dựng @Override public void characters(char ch[], int start, int length) throws SAXException { if (foundfirstname) { System.out.println("Characters: "+new String(ch,start,length)); foundfirstname=false; } if (foundlastname) { System.out.println("Characters: "+new String(ch,start,length)); IT Research Department @BKAP 2015 Trang 12 / 24 Processing XML Using Java foundlastname=false; } if (foundlocation) { System.out.println("Characters: "+new String(ch,start,length)); foundlocation=false; } } @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { } @Override public void endPrefixMapping(String prefix) throws SAXException { } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } @Override public void processingInstruction(String target, String data) throws SAXException { } @Override public void skippedEntity(String name) throws SAXException { } IT Research Department @BKAP 2015 Trang 13 / 24 Architecting Applications for the Web } Build Run ứng dụng Step 2: Sửdụng Instruc tions để đọc thị chương trình khác có định dạng: Employees.xml Allen Smith Alaska IT Research Department @BKAP 2015 Trang 14 / 24 Processing XML Using Java John Davis California Bob Thomson Kansas SaxHandler.java … @Override public void processingInstruction(String target, String data) throws SAXException { System.out.println("processingInstruction - target: "+target+", data: "+data); } … Build Run ứng dụng IT Research Department @BKAP 2015 Trang 15 / 24 Architecting Applications for the Web Step 3: Thông báo lỗi file XML sai cấu trúc Tạo lớp ErrorHandler.java để xử lý lỗi sai cấu trúc IntxmlnewOtherJavaJava Classđặt tên ErrorHandler /* * 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 intxml; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * * @author DELL */ public class ErrorHandler implements org.xml.sax.ErrorHandler{ @Override public void warning(SAXParseException exception) throws SAXException { showError("Warning", exception); } @Override public void error(SAXParseException exception) throws SAXException { showError("Error", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { showError("FatalError", exception); } private void showError(String errorType, SAXParseException e) { System.out.println(errorType + ": "+e.getMessage()); System.out.println("Line number: "+e.getLineNumber()+ " - Column: " + e.getColumnNumber()); } IT Research Department @BKAP 2015 Trang 16 / 24 Processing XML Using Java } Khai báo hàm Main INTXML.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 intxml; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * * @author DELL */ public class INTXML { /** * @param args the command line arguments */ public static void main(String[] args) { try { //Tạo SaxHandler xử lý nội dung SaxHandler sax = new SaxHandler(); //Tạo ErrorHandler thông báo lỗi ErrorHandler err = new ErrorHandler(); //Tạo SAX ParserFactory SAXParserFactory parserFactory = SAXParserFactory.newInstance(); //Tạo SAX Parser Factory khai báo SAXParser parser = parserFactory.newSAXParser(); //Khai báo XML Reader dựa SAXParser object XMLReader xmlReader = parser.getXMLReader(); //Xác định đối tượng chịu trách nhiệm xử lý lỗi phân tích XML xmlReader.setErrorHandler(err); //Xác định đối tượng chịu trách nhiệm xử lý nội dungXML IT Research Department @BKAP 2015 Trang 17 / 24 Architecting Applications for the Web xmlReader.setContentHandler(sax); //Tiến hành phân tích liệu nguồn cung cấp file XML xmlReader.parse(new InputSource("Employees.xml")); } catch (Exception e) { e.printStackTrace(); } } } Sửa cấu trúc file Employees.xml thành file sai cấu trúc Allen Smith Alaska John Davis California Bob Thomson Kansas Build and Run ứng dụng IT Research Department @BKAP 2015 Trang 18 / 24 Processing XML Using Java Bài 1.3 Xây dựng ứng dụng SAX: Duyệt file Personnels.xml Xây dựng lớp Filter kế thừa interface XMLFilterImpl để thay đổi attributes status = “donotcontact” element có deptid Step 1: Duyệt file Personnels.xml (làm theo step 1.1) SaxHandler.java kế thừa DefaultHandler package saxfilter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * * @author DELL */ IT Research Department @BKAP 2015 Trang 19 / 24 Architecting Applications for the Web public class SAXHandler extends DefaultHandler { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equals("employee")) { if (attributes.getValue("status").equals("contact")) { System.out.println("Contacting employee " + attributes.getValue("empid")); } } } } Hàm main lớp SAXFilter.java package saxfilter; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * * @author DELL */ public class SAXFilter { /** * @param args the command line arguments */ public static void main(String[] args) { try { SAXHandler sax = new SAXHandler(); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setContentHandler(sax); xmlReader.parse(new InputSource("Personnels.xml")); IT Research Department @BKAP 2015 Trang 20 / 24 Processing XML Using Java } catch (Exception e) { e.printStackTrace(); } } } Build and Run ứng dụng Step 2: Xây dựng lớp Filter Tạo lớp DataFilter.java kế thừa XMLFilterImpl package saxfilter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; /** * * @author DELL */ public class DataFilter extends XMLFilterImpl { @Override public void startElement(String uri, String name, String qName, Attributes atts) throws SAXException { AttributesImpl attsImpl = new AttributesImpl(atts); if (qName.equals("employee")) { if (atts.getValue("deptid").equals("3")) { attsImpl.setValue(3, "donotcontact"); } } super.startElement(uri, qName, qName, attsImpl); } IT Research Department @BKAP 2015 Trang 21 / 24 Architecting Applications for the Web } Sửa hàm main cho phép duyệt nội dung qua lớp DataFilter.java SAXFilter.java package saxfilter; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * * @author DELL */ public class SAXFilter { /** * @param args the command line arguments */ public static void main(String[] args) { try { SAXHandler sax = new SAXHandler(); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); DataFilter filter = new DataFilter(); filter.setParent(xmlReader); filter.setContentHandler(sax); filter.parse(new InputSource("Personnels.xml")); // // xmlReader.setContentHandler(sax); xmlReader.parse(new InputSource("Personnels.xml")); } catch (Exception e) { e.printStackTrace(); } } } IT Research Department @BKAP 2015 Trang 22 / 24 Processing XML Using Java Build and Run ứng dụng PHẦN 2: BÀI TẬP TỰ LÀM Viết chương trình sửdụng SAX để phân tích cấu trúc XML có dạng sau: In hình: Nội dung file xml Đầy đủ nội dung file xml với cấu trúc file theo SAX Sửdụng kế thừa theo ContentHandler DefaultHandler Vị trí element in IT Research Department @BKAP 2015 Trang 23 / 24 Architecting Applications for the Web Validate thông báo lỗi có lỗi cấu trúc XML Filter in hàng hóa có giá bán từ 400USD đến 600USD IT Research Department @BKAP 2015 Trang 24 / 24 ... SaxHandler(); //Tạo SAX ParserFactory SAXParserFactory parserFactory = SAXParserFactory.newInstance(); //Tạo SAX Parser Factory khai báo SAXParser parser = parserFactory.newSAXParser(); //Khai báo... ErrorHandler(); //Tạo SAX ParserFactory SAXParserFactory parserFactory = SAXParserFactory.newInstance(); //Tạo SAX Parser Factory khai báo SAXParser parser = parserFactory.newSAXParser(); //Khai báo... String(ch,start,length)); foundlocation=false; } } @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } @Override public void startPrefixMapping(String prefix, String uri)