1. Trang chủ
  2. » Công Nghệ Thông Tin

Thực hành sử dụng XML trong Java Lab 5

19 243 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 19
Dung lượng 793,57 KB

Nội dung

Processing XML Using Java Lab 05 Validating XML with JAXP Mục tiêu - Sử dụng XMLStreamReader đọc nội dung XML - Sử dụng XMLStreamWriter ghi file XML - Sử dụng XMLEventReader ghi nội dung file XML - Sử dụng JAXB Marshelling chuyển nội dung java object sang file XML - Sử dụng JAXB UnMarsher lấy nội dung file XML vào java object Phần I Bài tập step by step Bài 5.1 Sử dụng XMLStreamReader đọc nội dung file ccinfo.xml:  ccinfo.xml IT Research Department @BKAP 2015 Trang / 19 Architecting Applications for the Web  Output: Step 1: Tạo project java netbean  File  New Project  JavaJava Application  Project Name: Đặt tên Project StAX Step 2: Tạo File ccinfo.xml  Project  New  Other  XMLXML Document  ccinfo.xml XML DATA FOR CREDIT CARD INFORMATION > David McArthur 9921 5681 2521 8845 IT Research Department @BKAP 2015 Trang / 19 Processing XML Using Java CreditBank 06/10 Step 3: Tạo lớp BKXMLStreamReader để đọc in nội dụng file ccinfo.xml  BKXMLStreamReader.java package stax; import java.io.File; import java.io.FileInputStream; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; /** * * @author DELL */ public class BKXMLStreamReader { public static void StreamReader(File file) { try { //create XML Input Factory XMLInputFactory inputFactory = XMLInputFactory.newInstance(); //create XML Stream Reader form XMLInputFactory and source file ccinfo.xml XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new FileInputStream(file)); //Returns type of event an integer while (streamReader.hasNext()) { int eventType = streamReader.getEventType(); //check value of each event type switch (eventType) { //Event - start Element case 1: System.out.println("Event Type - START_ELEMENT(1)"); System.out.println("Start Element Name - " + streamReader.getLocalName()); //Event - end Element case 2: System.out.println("Event Type - END_ELEMENT(2)"); System.out.println("End Element Name - " + streamReader.getLocalName()); break; //Event - Processing Instruction case 3: System.out.println("Event Type – PROCESSING_INSTRUCTION(3)"); System.out.println("Processing Instruction Data - " + streamReader.getPIData()); break; //Event - Character case 4: System.out.println("Event Type - CHARACTERS(4)"); System.out.println("Character Data - " + streamReader.getText()); break; //Event - Comment case 5: System.out.println("Event Type - COMMENT(5)"); System.out.println("Comment Data - " + streamReader.getText()); IT Research Department @BKAP 2015 Trang / 19 Architecting Applications for the Web break; //Event - Space case 6: System.out.println("Event Type - SPACE(6)"); System.out.println("Space Info - " + streamReader.getText()); break; //Event - Start Document case 7: System.out.println("Event Type - START_DOCUMENT(7)"); System.out.println("Character Encoding Scheme - " + streamReader.getCharacterEncodingScheme()); System.out.println("Version - " + streamReader.getVersion()); break; } streamReader.next(); } int eventType = streamReader.getEventType(); //Event - End Document if (eventType == 8) { System.out.println("Event Type - END_DOCUMENT(8) - closing document"); streamReader.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } Step 4: Triển khai hàm main ứng dụng  StAX.java package stax; import java.io.File; /** * * @author DELL */ public class StAX { /** * @param args the command line arguments */ public static void main(String[] args) { try { //Reader File file = new File("ccinfo.xml"); BKXMLStreamReader bSR = new BKXMLStreamReader(); bSR.StreamReader(file); } catch (Exception e) { e.printStackTrace(); } } } IT Research Department @BKAP 2015 Trang / 19 Processing XML Using Java Step 5: Build and Run ứng dụng Bài 5.2 Sử dụng XMLStreamWriter Interface để ghi liệu file output.xml Step 1: Tạo lớp BKXMLStreamWriter để ghi liệu file xml  BKXMLStreamWriter.java IT Research Department @BKAP 2015 Trang / 19 Architecting Applications for the Web package stax; import java.io.File; import java.io.FileWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; /** * * @author DELL */ public class BKXMLStreamWriter { public static void StreamWriter(File file) { //create XML Output Factory XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { //create XML Stream Writer form XMLOutputFactory and recorded file xml XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file)); //Start write Document,Element,Value of Element, Attribute writer.writeStartDocument("1.0"); writer.writeStartElement("Employees"); writer.writeStartElement("employee"); writer.writeAttribute("id", "111"); writer.writeStartElement("firstName"); writer.writeCharacters("John"); writer.writeEndElement(); writer.writeStartElement("lasttName"); writer.writeCharacters("Peter"); writer.writeEndElement(); writer.writeStartElement("location"); writer.writeCharacters("London"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } } } Step 2: Triển khai hàm main ứng dụng package stax; import java.io.File; /** * * @author DELL */ public class StAX { /** * @param args the command line arguments */ IT Research Department @BKAP 2015 Trang / 19 Processing XML Using Java public static void main(String[] args) { try { //Reader File file = new File("ccinfo.xml"); BKXMLStreamReader bSR = new BKXMLStreamReader(); // bSR.StreamReader(file); //writer File fileWriter = new File("output.xml"); BKXMLStreamWriter bSW = new BKXMLStreamWriter(); bSW.StreamWriter(fileWriter); } catch (Exception e) { e.printStackTrace(); } } } Step 3: Build and Run ứng dụng Bài 5.3 Sử dụng XMLEventReader interator để phân tích in nội dung file xml  Employees.xml IT Research Department @BKAP 2015 Trang / 19 Architecting Applications for the Web  Output Step 1: Tạo lớp BKXMLEventReader để phân tích in nội dung Employees.xml  BKXMLEventReader.java package stax; import java.io.Reader; import java.util.Iterator; import javax.xml.namespace.QName; IT Research Department @BKAP 2015 Trang / 19 Processing XML Using Java import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; /** * * @author DELL */ public class BKXMLEventReader { public static void EventReader(Reader fileReader) { //create XML Input Factory XMLInputFactory factory = XMLInputFactory.newInstance(); try { //create XML Event Reader form XMLInputFactory and Reader file XMLEventReader reader = factory.createXMLEventReader(fileReader); //loop EventReader while (reader.hasNext()) { //get XMLEvent XMLEvent event = reader.nextEvent(); //Event is start element if (event.isStartElement()) { StartElement element = (StartElement) event; System.out.println("Start Element: " + element.getName()); Iterator iterator = element.getAttributes(); while (iterator.hasNext()) { Attribute attribute = (Attribute) iterator.next(); QName name = attribute.getName(); String value = attribute.getValue(); System.out.println("Attribute name/value: " + name + "/" + value); } } //Event is end element if (event.isEndElement()) { EndElement element = (EndElement) event; System.out.println("End element:" + element.getName()); } //Event is character if (event.isCharacters()) { Characters characters = (Characters) event; System.out.println("Text: " + characters.getData()); } } } catch (XMLStreamException ex) { ex.printStackTrace(); } } } IT Research Department @BKAP 2015 Trang / 19 Architecting Applications for the Web  Cấu trúc project sau hoàn thành Step 2: Triển khai hàm main ứng dụng package stax; import java.io.File; import java.io.FileReader; import java.io.Reader; /** * * @author DELL */ public class StAX { /** * @param args the command line arguments */ public static void main(String[] args) { try { //Reader File file = new File("ccinfo.xml"); BKXMLStreamReader bSR = new BKXMLStreamReader(); // bSR.StreamReader(file); //writer File fileWriter = new File("output.xml"); BKXMLStreamWriter bSW = new BKXMLStreamWriter(); // bSW.StreamWriter(fileWriter); //EventReader Reader fileReader = new FileReader(new File("Employees.xml")); BKXMLEventReader bER = new BKXMLEventReader(); bER.EventReader(fileReader); } catch (Exception e) { e.printStackTrace(); } } } Step 3: Build and Run ứng dụng IT Research Department @BKAP 2015 Trang 10 / 19 Processing XML Using Java Bài 5.4 Sử dụng JAXB để chuyển java object thành file xml IT Research Department @BKAP 2015 Trang 11 / 19 Architecting Applications for the Web Step 1: Tạo project java netbean  File  New Project  JavaJava Application  Project Name: Đặt tên Project JAXB Step 2: Tạo java object JAXBEmployee sử dụng để tạo file xml  JAXBEmployee.java package jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * * @author DELL */ @XmlRootElement(name="employee") @XmlAccessorType(XmlAccessType.FIELD) public class JAXBEmployee { private Integer id; private String firstName; private String lastName; private double income; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public double getIncome() { return income; } IT Research Department @BKAP 2015 Trang 12 / 19 Processing XML Using Java public void setIncome(double income) { this.income = income; } } Step 3: Tạo java object Map  EmployeeMap.java package jaxb; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * * @author DELL */ @XmlRootElement(name="employees") @XmlAccessorType(XmlAccessType.FIELD) public class EmployeeMap { private Map employeeMap = new HashMap(); public Map getEmployeeMap() { return employeeMap; } public void setEmployeeMap(Map employeeMap) { this.employeeMap = employeeMap; } } Step 4: Triển khai hàm main ứng dụng để tạo file JAXBMarshalOutput.xml từ JAXBEmployee EmployeeMap package jaxb; import java.io.File; import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; /** * * @author DELL */ public class JAXB { /** IT Research Department @BKAP 2015 Trang 13 / 19 Architecting Applications for the Web * @param args the command line arguments */ public static void main(String[] args) { //create HashMap HashMap map = new HashMap(); //create object JAXBEmployee emp1 JAXBEmployee emp1 = new JAXBEmployee(); //Set value to object emp1 emp1.setId(1); emp1.setFirstName("Allen"); emp1.setLastName("Smith"); emp1.setIncome(100.0); //create object JAXBEmployee emp2 JAXBEmployee emp2 = new JAXBEmployee(); //Set value to object emp2 emp2.setId(2); emp2.setFirstName("John"); emp2.setLastName("Mclane"); emp2.setIncome(200.0); map.put(1, emp1); map.put(2, emp2); //add employee in map EmployeeMap employeeMap = new EmployeeMap(); employeeMap.setEmployeeMap(map); try { //create JAXB context and instantiate marshaller JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //write to System.out jaxbMarshaller.marshal(employeeMap, System.out); //write to File JAXBMarshalOutput.xml jaxbMarshaller.marshal(employeeMap, new File("JAXBMarshalOutput.xml")); } catch (JAXBException ex) { ex.printStackTrace(); } } } Step 5: Build and Run ứng dụng IT Research Department @BKAP 2015 Trang 14 / 19 Processing XML Using Java IT Research Department @BKAP 2015 Trang 15 / 19 Architecting Applications for the Web Bài 5.5 Sử dụng JAXB lấy liệu từ file xml đẩy vào java object in hình  Employees.xml  Output: IT Research Department @BKAP 2015 Trang 16 / 19 Processing XML Using Java Step 1: Tạo object Employee để lấy liệu element employee file xml  Employee.java package jaxb; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; /** * * @author DELL */ public class Employee { private int id; private String firstName; private String lastName; private String location; public Employee(){} public Employee(int id, String firstName, String lastName,String location){ super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.location = location; } //getter and setter Attribute id @XmlAttribute public int getId() { return id; } public void setId(int id) { this.id = id; } //getter and setter element firstname @XmlElement public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } //getter and setter element lastname @XmlElement public String getLastName() { IT Research Department @BKAP 2015 Trang 17 / 19 Architecting Applications for the Web return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } //getter and setter element location @XmlElement public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } Step 2: Tạo List chứa object employee  Employees.java package jaxb; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * * @author DELL */ @XmlRootElement(name = "employees") public class Employees { private List employees; public Employees(){} public Employees(List employees){ super(); this.employees=employees; } @XmlElement(name = "employee") public List getEmployees() { return employees; } public void setEmployees(List employees) { this.employees = employees; } } Step 3: Triển khai hàm main ứng dụng để lấy liệu từ file xml vào java object package jaxb; import java.io.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; IT Research Department @BKAP 2015 Trang 18 / 19 Processing XML Using Java import javax.xml.bind.Unmarshaller; /** * * @author DELL */ public class JAXB { /** * @param args the command line arguments */ public static void main(String[] args) { //Create File form Employees.xml File file = new File("Employees.xml"); try { //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); //Create Unmarshaller Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); //Get List Employees form Unmarshaller and file Employees emp = (Employees) jaxbUnmarshaller.unmarshal(file); System.out.println("employees:"); List listemp = emp.getEmployees(); //Print each employee in list Employees for (Employee empl : listemp) { System.out.println(empl.getId() + " " + empl.getFirstName() + " " + empl.getLastName() + " " + empl.getLocation()); } } catch (JAXBException ex) { ex.printStackTrace(); } } } Step 4: Build and Run ứng dụng IT Research Department @BKAP 2015 Trang 19 / 19 ... Using Java Step 5: Build and Run ứng dụng Bài 5. 2 Sử dụng XMLStreamWriter Interface để ghi liệu file output .xml Step 1: Tạo lớp BKXMLStreamWriter để ghi liệu file xml  BKXMLStreamWriter .java. .. javax .xml. stream.XMLEventReader; import javax .xml. stream.XMLInputFactory; import javax .xml. stream.XMLStreamException; import javax .xml. stream.events.Attribute; import javax .xml. stream.events.Characters;... import java. util.Map; import javax .xml. bind.annotation.XmlAccessType; import javax .xml. bind.annotation.XmlAccessorType; import javax .xml. bind.annotation.XmlRootElement; /** * * @author DELL */ @XmlRootElement(name="employees")

Ngày đăng: 07/05/2018, 16:19

TỪ KHÓA LIÊN QUAN

w