Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 22 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
22
Dung lượng
756,37 KB
Nội dung
Processing XML Using JavaLab02 Document Object Model Mục tiêu - Chỉ rõ kiểu Node - Cách lấy giá trị Node file XML - Cách tạo Node giá trị Node - Cách cập nhật giá trị Node giá trị Attribute - Cách xóa Node - Sửdụng ErrorHandler DOM Phần I Bài tập step by step Bài 2.1 In kiểu Node có file Employees.xml DOM: IT Research Department @BKAP 2015 Trang / 22 Architecting Applications for the Web Step 1: Tạo project java netbean File New Project Java Java Application Project Name: Đặt tên project DOMExample Step 2: Tạo file Employees.xml Project New XML XML Document Employees.xml ]> Allen Smith Alaska M John Davis California M Bob Thomson Kansas IT Research Department @BKAP 2015 Trang / 22 Processing XML Using Java M Step 3: Tạo lớp NodeTypes.java in kiểu node package domexample; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author DELL */ public class NodeTypes { public static void printNodes(Document n) { printElement((Node) n, " "); } public static void printElement(Node n, String indent) { int type = n.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: System.out.println(indent + "CDATA_SECTION_NODE"); break; case Node.COMMENT_NODE: System.out.println(indent + "COMMENT_NODE"); break; case Node.DOCUMENT_FRAGMENT_NODE: System.out.println(indent + "DOCUMENT_FRAGMENT_NODE"); break; case Node.DOCUMENT_NODE: System.out.println(indent + "DOCUMENT_NODE"); break; case Node.DOCUMENT_TYPE_NODE: System.out.println(indent + "DOCUMENT_TYPE_NODE"); break; IT Research Department @BKAP 2015 Trang / 22 Architecting Applications for the Web case Node.ELEMENT_NODE: System.out.println(indent + "ELEMENT_NODE"); break; case Node.ENTITY_NODE: System.out.println(indent + "ENTITY_NODE"); break; case Node.ENTITY_REFERENCE_NODE: System.out.println(indent + "ENTITY_REFERENCE_NODE"); break; case Node.NOTATION_NODE: System.out.println(indent + "NOTATION_NODE"); break; case Node.PROCESSING_INSTRUCTION_NODE: System.out.println(indent + "PROCESSING_INSTRUCTION_NODE"); break; case Node.TEXT_NODE: System.out.println(indent + "TEXT_NODE"); break; default: System.out.println(indent + "Unknown node"); break; } //Lấy danh sách Node cho Node cha NodeList list = n.getChildNodes(); Element item = null; for (int i = 0; i < list.getLength(); i++) { printElement(list.item(i), indent + " "); } } } Step 4: Triển khai hàm main chương trình DOMExample.java package domexample; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; IT Research Department @BKAP 2015 Trang / 22 Processing XML Using Java /** * * @author DELL */ public class DOMExample { /** * @param args the command line arguments */ public static void main(String[] args) { try { //Khởi tạo file, trỏ vào file cần phân tích File fXmlFile = new File("Employees.xml"); //Khởi tạo Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Khởi tạo DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); //Đẩy nội dung vào Document Document doc = builder.parse(fXmlFile); //In kiểu Node, gọi method printNodes lớp NodeTypes NodeTypes node = new NodeTypes(); node.printNodes(doc); } catch (Exception ex) { ex.printStackTrace(); } } } Project sau hoàn thành IT Research Department @BKAP 2015 Trang / 22 Architecting Applications for the Web Step 5: Build Run ứng dụng Bài 2.2 Sửdụng method Node Interface để in giá trị Element Node “firstname” Element Node “employee” file Employees.xml (trong project 2.1) Step 1: Tạo lớp SeekingNodes.java để in giá trị Element Node “firstname” Domexample New Other Java Java Class SeekingNodes.java package domexample; IT Research Department @BKAP 2015 Trang / 22 Processing XML Using Java import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * * @author DELL */ public class SeekingNodes { public static void printNodeValue(Document doc){ //Lấy danh sách Element Node “employee” NodeList listemp = doc.getElementsByTagName("employee"); Element emp = null; //Duyệt node employee for (int i = 0; i < listemp.getLength(); i++) { emp = (Element) listemp.item(i); //Lấy giá trị node firstname node employee String FName = emp.getElementsByTagName("firstname").item(0).getFirstChild().getNodeValue() ; System.out.println(FName); } } } Step 2: Triển khai hàm main chương trình DOMExample.java package domexample; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; /** * * @author DELL */ public class DOMExample { IT Research Department @BKAP 2015 Trang / 22 Architecting Applications for the Web /** * @param args the command line arguments */ public static void main(String[] args) { try { //Khởi tạo file, trỏ vào file cần phân tích File fXmlFile = new File("Employees.xml"); //Khởi tạo Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Khởi tạo DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); //Đẩy nội dung vào Document Document doc = builder.parse(fXmlFile); //In kiểu Node, gọi method printNodes lớp NodeTypes NodeTypes node = new NodeTypes(); node.printNodes(doc); //In giá trị Node firstname SeekingNodes node = new SeekingNodes (); node.printNodeValue(doc); } catch (Exception ex) { ex.printStackTrace(); } } } Project sau hoàn thành Step 3: Build and Run ứng dụng IT Research Department @BKAP 2015 Trang / 22 Processing XML Using Java Bài 2.3 Tạo node file Employees.xml Cập nhật node file Employees.xml: viết hoa giá trị node firstname Cập nhật giá trị Attribute Element employee file Employees.xml với điều kiện: Nếu gender M ID = “M…”, F ID = “F…” IT Research Department @BKAP 2015 Trang / 22 Architecting Applications for the Web Xóa Node file Employees.xml: Xóa node location element employee IT Research Department @BKAP 2015 Trang 10 / 22 Processing XML Using Java Phần 1: Tạo node file Employees.xml Step 1: Tạo lớp ControlNodes.java domexample New Other Java Java Class ControlNodes.java package domexample; import java.io.FileOutputStream; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; /** * * @author DELL */ public class ControlNodes { public static void CreateNode(Document doc) { //Get Element Element element = doc.getDocumentElement(); //Create node employee Node node = doc.createElement("employee"); //Create child node employee: firstname Node nodefn = node.appendChild(doc.createElement("firstname")); Text textfn = doc.createTextNode("Michelle"); nodefn.appendChild(textfn); //Create child node employee: lastname Node nodeln = node.appendChild(doc.createElement("lastname")); Text textln = doc.createTextNode("Sawyer"); nodeln.appendChild(textln); IT Research Department @BKAP 2015 Trang 11 / 22 Architecting Applications for the Web //Create child node employee: location Node nodel = node.appendChild(doc.createElement("location")); Text textlocation = doc.createTextNode("Kannas"); nodel.appendChild(textlocation); //Create child node employee: gender Node nodeg = node.appendChild(doc.createElement("gender")); Text textgender = doc.createTextNode("F"); nodeg.appendChild(textgender); //Add Node element.appendChild(node); //Call Save XML Method SaveXMLDocument(doc); } private static void SaveXMLDocument(Document doc) { try { // create DOMSource for source XML document Source xmlSource = new DOMSource(doc); // create StreamResult for transformation result Result result = new StreamResult(new FileOutputStream("Employees.xml")); // create TransformerFactory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create Transformer for transformation Transformer transformer = transformerFactory.newTransformer(); // transform and deliver content to client transformer.transform(xmlSource, result); } catch (Exception ex) { ex.printStackTrace(); } } } Step 2: Triển khai hàm main ứng dụng DOMExample.jav package domexample; import java.io.File; import javax.xml.parsers.DocumentBuilder; IT Research Department @BKAP 2015 Trang 12 / 22 Processing XML Using Java import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; /** * * @author DELL */ public class DOMExample { /** * @param args the command line arguments */ public static void main(String[] args) { try { File fXmlFile = new File("Employees.xml"); //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(fXmlFile); // NodeTypes node = new NodeTypes(); // node.printNodes(doc); // SeekingNodes node = new SeekingNodes(); // node.printNodeValue(doc); ControlNodes cnode = new ControlNodes(); cnode.CreateNode(doc); } catch (Exception ex) { ex.printStackTrace(); } } } Project sau hoàn thành IT Research Department @BKAP 2015 Trang 13 / 22 Architecting Applications for the Web Step 3: Build and Run ứng dụng Phần 2: Cập nhật Node Step 1: Xây dựng thêm method UpdateElementValue ControlNodes.java ControlNodes.java public static void UpdateElementValue(Document doc){ NodeList listemp = doc.getElementsByTagName("employee"); Element emp = null; //loop for each employee for (int i = 0; i < listemp.getLength(); i++) { emp = (Element) listemp.item(i); Node nodefn = emp.getElementsByTagName("firstname").item(0).getFirstChild(); nodefn.setNodeValue(nodefn.getNodeValue().toUpperCase()); } SaveXMLDocument(doc); } Step 2: Từ main gọi thực method UpdateElementValue public static void main(String[] args) { try { File fXmlFile = new File("Employees.xml"); //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); IT Research Department @BKAP 2015 Trang 14 / 22 Processing XML Using Java factory.setValidating(false); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(fXmlFile); NodeTypes node = new NodeTypes(); node.printNodes(doc); SeekingNodes node = new SeekingNodes(); node.printNodeValue(doc); ControlNodes cnode = new ControlNodes(); cnode.CreateNode(doc); cnode.UpdateElementValue(doc); } catch (Exception ex) { ex.printStackTrace(); } // // // // // } Step 3: Build and Run ứng dụng Phần 3: Cập nhật giá trị Attribute Step 1: Xây dựng thêm method UpdateAttributeValue ControlNodes.java IT Research Department @BKAP 2015 Trang 15 / 22 Architecting Applications for the Web ControlNodes.java public static void UpdateAttributeValue(Document doc){ NodeList listemp = doc.getElementsByTagName("employee"); Element emp = null; //loop for each employee for (int i = 0; i < listemp.getLength(); i++) { emp = (Element) listemp.item(i); String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue(); if (gender.equalsIgnoreCase("M")) { //prefix id attribute with M emp.setAttribute("id", "M"+emp.getAttribute("id")); } else { //prefix id attribute with F emp.setAttribute("id", "F"+emp.getAttribute("id")); } } SaveXMLDocument(doc); } Step 2: Gọi method UpdateAttributeValue từ hàm main public static void main(String[] args) { try { File fXmlFile = new File("Employees.xml"); //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(fXmlFile); // NodeTypes node = new NodeTypes(); // node.printNodes(doc); // SeekingNodes node = new SeekingNodes(); // node.printNodeValue(doc); ControlNodes cnode = new ControlNodes(); // cnode.CreateNode(doc); // cnode.UpdateElementValue(doc); cnode.UpdateAttributeValue(doc); } catch (Exception ex) { ex.printStackTrace(); IT Research Department @BKAP 2015 Trang 16 / 22 Processing XML Using Java } } Step 3: Build and Run ứng dụng Phần 4: Xóa Node Step 1: Xây dựng thêm method RemoveNodeFromDOMDocument lớp ControlNodes.java ControlNodes.java public static void RemoveNodeFormDOMDocumnet(Document doc){ //retrieve the element location for the first employee Element element = (Element) doc.getElementsByTagName("location").item(0); //Remove the specific node element.getParentNode().removeChild(element); //Normalize the DOM tree, puts all text nodes in full depth of the sub_tree underneath this node doc.normalize(); SaveXMLDocument(doc); IT Research Department @BKAP 2015 Trang 17 / 22 Architecting Applications for the Web } Step 2: Triển khai gọi methode RemoveNodeFromDOMDocument từ hàm main public static void main(String[] args) { try { File fXmlFile = new File("Employees.xml"); //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(fXmlFile); // NodeTypes node = new NodeTypes(); // node.printNodes(doc); // SeekingNodes node = new SeekingNodes(); // node.printNodeValue(doc); ControlNodes cnode = new ControlNodes(); // cnode.CreateNode(doc); // cnode.UpdateElementValue(doc); // cnode.UpdateAttributeValue(doc); cnode.RemoveNodeFormDOMDocumnet(doc); } catch (Exception ex) { ex.printStackTrace(); } } Step 3: Build and Run ứng dụng IT Research Department @BKAP 2015 Trang 18 / 22 Processing XML Using Java Bài 2.4 Xây dựng lớp Handling Errors ứng dụng DOM: Bắt lỗi sai cấu trúc file Employees.xml ứng dụng DOM Step 1: Xây dựng lớp DOMErrorHandler.java implements ErrorHandler DOMErrorHandler.java package domexample; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * * @author DELL */ public class DOMErrorHandler 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); } IT Research Department @BKAP 2015 Trang 19 / 22 Architecting Applications for the Web @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()); } } Cấu trúc Project sau hoàn thành Step 2: Set ErrorHandler cho DocumentBuilder hàm main public static void main(String[] args) { try { File fXmlFile = new File("Employees.xml"); //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder(); //Set ErrorHandler to DocumentBuilder builder.setErrorHandler(new DOMErrorHandler()); Document doc = builder.parse(fXmlFile); // NodeTypes node = new NodeTypes(); // node.printNodes(doc); // SeekingNodes node = new SeekingNodes(); // node.printNodeValue(doc); ControlNodes cnode = new ControlNodes(); IT Research Department @BKAP 2015 Trang 20 / 22 Processing XML Using Java // // // cnode.CreateNode(doc); cnode.UpdateElementValue(doc); cnode.UpdateAttributeValue(doc); cnode.RemoveNodeFormDOMDocumnet(doc); } catch (Exception ex) { ex.printStackTrace(); } } Step 3: Build and Run ứng dụng Phần II Bài Tập Tự Làm Viết ứng dụngsửdụng DOM thao tác với file HangHoa.xml IT Research Department @BKAP 2015 Trang 21 / 22 Architecting Applications for the Web In kiểu node sửdụng In giá trị node tenHang, nhaSX Tạo Node: Cập nhật giá trị node nhaSX thành chữ in hoa, cập nhật giá trị Attribute Element hangHoa thành id = “H…” Xóa node tenHang element hangHoa có ID = “H003” IT Research Department @BKAP 2015 Trang 22 / 22 ... ứng dụng Phần II Bài Tập Tự Làm Viết ứng dụng sử dụng DOM thao tác với file HangHoa .xml IT Research Department @BKAP 20 15 Trang 21 / 22 Architecting Applications for the Web In kiểu node sử dụng. .. Department @BKAP 20 15 Trang 10 / 22 Processing XML Using Java Phần 1: Tạo node file Employees .xml Step 1: Tạo lớp ControlNodes .java domexample New Other Java Java Class ControlNodes .java package... java. io.FileOutputStream; import javax .xml. transform.Result; import javax .xml. transform.Source; import javax .xml. transform.Transformer; import javax .xml. transform.TransformerFactory; import javax .xml. transform.dom.DOMSource;