Bài giàng Cline Sever - Chương 5: XML DOM - Trần Kim Chi

Tính chất và đặc điểm DOM node tree và node types XML DOM và Javascript XML In Server Nền tảng DOM (Document Object Model) là một dạng chuẩn được định nghĩa bởi W3C, chỉ như XML DOM không được thiết kế đặc trưng cho Java (không như SAX) DOM là cross-platform và cross-language  Dùng OMG `s IDL để định nghĩa những giao diện  IDL là ngôn ngữ nối kết Đặc điểm của DOM Truy xuất tài liệu XML như một cấu trúc cây Hình thành hầu hết là những nút thành phần và những nút văn bản Có thể “walk“ trong cây từ trước ra sau Cần bộ nhớ lớn Dùng nó để walking và modifying cây

pdf121 trang | Chia sẻ: candy98 | Lượt xem: 696 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Bài giàng Cline Sever - Chương 5: XML DOM - Trần Kim Chi, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
1 XML DOM 27.01.2013 2 Nội dung Tính chất và đặc điểm DOM node tree và node types XML DOM và Javascript XML In Server 27.01.2013 3 Nền tảng DOM (Document Object Model) là một dạng chuẩn được định nghĩa bởi W3C, chỉ như XML DOM không được thiết kế đặc trưng cho Java (không như SAX) DOM là cross-platform và cross-language  Dùng OMG `s IDL để định nghĩa những giao diện  IDL là ngôn ngữ nối kết 27.01.2013 4 Đặc điểm của DOM Truy xuất tài liệu XML như một cấu trúc cây Hình thành hầu hết là những nút thành phần và những nút văn bản Có thể “walk“ trong cây từ trước ra sau Cần bộ nhớ lớn Dùng nó để walking và modifying cây 27.01.2013 5 Đặc điểm của DOM 27.01.2013 6 Dom trong Action 27.01.2013 7 DOM cây và nút Tài liệu XML được hiển thị như một cây Cây được tạo thành từ nút. Nút trên cùng gọi là nút gốc (root). Mỗi nút (ngoại trừ nút gốc) có 1 nút cha ( parent node). Một nút cha có thể có nhiều nút con (children node). Nút lá là nút không có nút con. Siblings là những nút có cùng nút cha 27.01.2013 8 DOM cây và nút Ví Dụ: Xác định các loại nút: Everyday Italian Giada De Laurentiis 2005 30.00 27.01.2013 9 Loại nút Có 12 loại kiểu nút khác nhau  Document node  Document Fragment node  Element node  Attribute node  Text node  Comment node  Processing instruction node  Document type node  Entity node  Entity reference node  CDATA section node  Notation node 27.01.2013 10 DOM cây phân cấp Một document node chứa  Một element node (nút thành phần gốc)  Một hay nhiều processing instruction node Một element node có thể chứa  Những element node khác  Một hay nhiều text node  Một hay nhiều attribute node Một attribute node có thể chứa  Một text node 27.01.2013 11 Ví dụ XML Document 27.01.2013 12 Ví dụ DOM cây XML Document node  Element node “people“  Element node “person“  Element node “name“  Element node “first_name“ text node “Alan“  Element node “last_name“ text node “Turing“  Element node “profession“  Text node “computer scientist“  Attribute node “born“  Text node “1912“ 27.01.2013 13 LÀM VIỆC VỚI DOM XML Parser XML parser đọc XML, và chuyển nó thành đối tượng XML mà có thể truy xuất với JavaScript. 14 DOM Và JAVASCRIPT 1- Kỹ thuật client: thỏa mãn IE và FF var xmlDoc; function load () { //for IE7 if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.load("places.xml"); var xmlObj = xmlDoc.documentElement; Show (xmlDoc); } //for FF else if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("","",null) ; xmlDoc.onload = function (evt) {Show (xmlDoc);}; xmlDoc.load("places.xml");} } 15 2- Kỹ thuật Server: thỏa mãn các trình duyệt với yêu cầu: tệp XML và JS đặt ở Server function loadXMLDoc(dname){ if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else {xhttp=new ActiveXObject("Microsoft.XMLHTTP");} xhttp.open("GET",dname,false); xhttp.send(); return xhttp.responseXML; } Kỹ thuật chính là sử dụng đối tượng XMLHttpRequest DOM Và JAVASCRIPT 16 An External JavaScript for loadXMLDoc()  The file is called "loadxmldoc.js", and will be loaded in the head section of an HTML page. Then, the loadXMLDoc() function can be called from a script in the page.  The following example uses the loadXMLDoc() function to load books.xml: xmlDoc=loadXMLDoc("books.xml"); code goes here.....  DOM Và JAVASCRIPT 17 The loadXMLString() Function  To make the code from the previous page simpler to maintain (and check for older browsers). function loadXMLString(txt) { if (window.DOMParser) { parser=new DOMParser(); xmlDoc=parser.parseFromString(txt,"text/xml"); } else // Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.loadXML(txt); } return xmlDoc; } DOM Và JAVASCRIPT 18 An External JavaScript for loadXMLString()  We have stored the loadXMLString() function in a file called "loadxmlstring.js".  text="" text=text+""; text=text+"Everyday Italian"; text=text+"Giada De Laurentiis"; text=text+"2005"; text=text+""; text=text+""; xmlDoc=loadXMLString(text); code goes here..... DOM Và JAVASCRIPT 19 Ví dụ : tệp books.xml và LoadXMM.htm với hàm Javascript đặt ở Server Books.xml Everyday Italian Giada De Laurentiis 2005 30.00 20 Ví dụ : tệp books.xml và LoadXMM.htm với hàm Javascript đặt ở Server if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // IE 5/6 { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","books.xml",false); xhttp.send(); xmlDoc=xhttp.responseXML; 21 Ví dụ : tệp books.xml và LoadXMM.htm với hàm Javascript đặt ở Server Load an XML String  The following code loads and parses an XML string:  Example  if (window.DOMParser) { parser=new DOMParser(); xmlDoc=parser.parseFromString(text,"text/xml"); } else // Internet Explorer { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.loadXML(text); } 22 Thao tác trên cây XML Tệp XML LOAD 1- Truy cập các node, thuộc tính 2- Hiệu chỉnh dữ liệu node, thuộc tính 3- Thêm node 4- Xóa node 23 Truy cập node của cây XML Giả sử : xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); Hay xmlDoc= return xhttp.responseXML; a) Truy cập nút gốc : xmlDoc.documentElement Từ nút gốc, hoặc một nút bất kỳ nào đó (kiểu object) - sử dụng các thuộc tính firstChild, lastChild, nextSibling, previousSibling để truy cấp các nút con của nút nầy. - sử dụng tập hợp childNodes để truy cập vào mảng các nút con b) Truy cập nút bất kỳ : từ xmlDoc - Sử dụng các phương thức :getElementsByTagName - Sử dụng phương thức: selectSingleNode(path) // từ gốc->nút Từ nút cụ thể này, sử dụng thuộc tính childNodes để truy cập đến các nút con của nó. 24 Truy cập nút=> tên nút, giá trị... Giả sử x là một biến object trỏ đến một node, ta có:  x.nodeName - the name of x  x.nodeValue - the value of x  x.parentNode - the parent node of x (object)  x.childNodes - the child nodes of x (array)  x.attributes - the attributes nodes of x (array) Lưu ý: giả sử x là một nút chứa phần tử text (không chứa nút con) thì giá trị của nó là: x.childNodes[0].nodeValue 25 Truy cập nút=> tên nút, giá trị...  A function, loadXMLDoc(), in an external JavaScript is used to load the XML file.  Access a node using its index number in a node list  Loop through nodes using the length property  See the node type of an element  Loop through element nodes  Loop through element nodes using node relationships 26 Truy cập nút=> tên nút, giá trị...  Phương thức getElementsByTagName() : trả về tất cả các phần tử với tên Tag được chỉ định  Cú pháp: node.getElementsByTagName("tagname");  Ví dụ  Trả về tất cả các phần tử dưới nút x x.getElementsByTagName("title"); under the x node.  Trả về tất cả các phần tử trong tài liệu XML xmlDoc.getElementsByTagName("title"); 27 Truy cập nút=> tên nút, giá trị... DOM Node List  getElementsByTagName(): trả về một danh sách node. Một danh sách node là một mảng của nhiều node.  Ví dụ xmlDoc=loadXMLDoc("books.xml"); //x lưu trữ danh sách các node của title x=xmlDoc.getElementsByTagName("title"); //Truy xuất phần tử thứ 3 của title y=x[2];  Note: The index starts at 0. 28 Truy cập nút=> tên nút, giá trị... DOM Node List Length  Thuộc tính length định nghĩa chiều dài của danh sách node  Ví dụ  xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title"); for (i=0;i<x.length;i++) { document.write(x[i].childNodes[0].nodeValue); document.write(“ "); } 29 Truy cập thông tin của nút=> tên nút, giá trị...  Get the node name of an element node  Get the text from a text node  Change the text in a text node  Get the node name and type of an element node 30 The nodeValue Property  Lấy giá trị của một phần tử.  Ví dụ: lấy giá trị của phần tử đầu  xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].chil dNodes[0]; txt=x.nodeValue; 31 Change the Value of an Element  Dùng để thay đổi giá trị của node.  Ví dụ: thay đổi giá trị phần tử đầu tiên xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].child Nodes[0]; x.nodeValue="Easy Cooking"; 32 The nodeType Property Dùng để chỉ định kiểu node, nodeType là chỉ đọc. Các kiểu node quan trọng: Node type NodeType Element 1 Attribute 2 Text 3 Comment 8 Document 9 33 Navigating DOM Nodes  Việc truy xuất các node trong cây thông qua mối quan hệ giữa các node.  Trong XML DOM, quan hệ giữa các node là:  parentNode  childNodes  firstChild  lastChild  nextSibling  previousSibling 34 Navigating DOM Nodes DOM - Parent Node  Tất cả các node có duy nhất 1 cha.  Ví dụ: Lấy tên node cha của xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; document.write(x.parentNode.nodeName); 35 Get the First Child Element //check if the first node is an element node function get_firstChild(n) { y=n.firstChild; while (y.nodeType!=1) { y=y.nextSibling; } return y; } xmlDoc=loadXMLDoc("books.xml"); x=get_firstChild(xmlDoc.getElementsByTagName("book")[0]); document.write(x.nodeName); 36 Avoid Empty Text Nodes  To avoid navigating to empty text nodes (spaces and new-line characters between element nodes), we use a function that checks the node type:  function get_nextSibling(n) { y=n.nextSibling; while (y.nodeType!=1) { y=y.nextSibling; } return y; } 37 Get an Element Value  Phương thức getElementsByTagName(): trả về danh sách node chứa tất cả các phần tử với tên tag được chỉ định theo thứ tự mà nó xuất hiện trong tài liệu nguồn.  Ví dụ: lấy phần tử đầu: xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0];  Thuộc tính childNodes trả về danh sách các node con. x=xmlDoc.getElementsByTagName("title")[0]; y=x.childNodes[0]; 38 Get an Attribute Value - getAttribute()  Phương thức getAttribute() trả về giá trị thuộc tính.  Ví dụ xmlDoc=loadXMLDoc("books.xml"); txt=xmlDoc.getElementsByTagName("title")[0].getAttribut e("lang"); 39 Get an Attribute Value - getAttributeNode()  getAttributeNode() : trả về thuộc tính text node  Ví dụ: lấy giá trị text của thuộc tính “lang” của phần tử đầu xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].getAt tributeNode("lang"); txt=x.nodeValue; 40 Change Node Values Thay đổ giá trị của một phần tử.  Để thay đổi text của 1 phần tử thì ta thay đổi value của node con.  Ví dụ: thay đổi text node của đầu xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue="Easy Cooking"; 41 Change the Value of an Attribute  Trong DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.  The way to change the value of an attribute, is to change its text value.  This can be done using the setAttribute() method or using the nodeValue property of the attribute node.  Ví dụ: thay đổi thuộc tính category của phần tử xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName('book'); x[0].setAttribute("category","food"); 42 Change an Attribute Using nodeValue  The nodeValue property can be used to change the value of a attribute node:  Example xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0] y=x.getAttributeNode("category"); y.nodeValue="food"; 43 Remove an Element Node  removeChild(): xóa node được chỉ định. Khi xóa tất cả các node con cũng xóa theo  Ví dụ: xóa phần tử đầu xmlDoc=loadXMLDoc("books.xml"); y=xmlDoc.getElementsByTagName("book")[0]; xmlDoc.documentElement.removeChild(y); 44 Remove Myself - Remove the Current Node  Ví dụ: xóa node sử dụng parentNode xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; x.parentNode.removeChild(x); 45 Remove a Text Node  removeChild() : cũng được sử dụng để xóa một text node.  Ví dụ: xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0]; y=x.childNodes[0]; x.removeChild(y); 46 Clear a Text Node  Thuộc tính nodeValue có thể dùng để thay đổi hay xóa value of a text node:  Ví dụ: xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].child Nodes[0]; x.nodeValue=""; 47 Remove an Attribute Node by Name  removeAttribute(name): dùng để xóa an attribute node by its name.  Ví dụ: xóa thuộc tính ‘category’ của xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book"); x[0].removeAttribute("category"); 48 Remove Attribute Nodes by Object  The removeAttributeNode(node) method is used to remove an attribute node, using the node object as parameter.  Example: xóa tất cả các thuộc tính của tất cả các phần tử xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book"); for (i=0;i<x.length;i++) { while (x[i].attributes.length>0) { attnode=x[i].attributes[0]; old_att=x[i].removeAttributeNode(attnode); } }  49 Replace an Element Node  replaceChild(): thay thế một node  Ví dụ: thay thế phần tử đầu  xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.documentElement; //create a book element, title element and a text node newNode=xmlDoc.createElement("book"); newTitle=xmlDoc.createElement("title"); newText=xmlDoc.createTextNode("A Notebook"); //add the text node to the title node, newTitle.appendChild(newText); //add the title node to the book node newNode.appendChild(newTitle); y=xmlDoc.getElementsByTagName("book")[0] //replace the first book node with the new node x.replaceChild(newNode,y); 50 Replace Data In a Text Node  replaceData(): thay thế dữ liệu trong một text node.  Gồm 3 tham số:  offset - Where to begin replacing characters. Offset value starts at zero  length - How many characters to replace  string - The string to insert  Ví dụ: xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].child Nodes[0]; x.replaceData(0,8,"Easy"); 51 Use the nodeValue Property Instead  nodeValue property: thay thế dữ liệu của 1 text node.  Ví dụ: xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].child Nodes[0]; x.nodeValue="Easy Italian"; 52 Create a New Element Node  createElement(): tạo một node mới  Example  xmlDoc=loadXMLDoc("books.xml"); newel=xmlDoc.createElement("edition"); x=xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newel); 53 Create a New Attribute Node  The createAttribute() is used to create a new attribute node:  Example  xmlDoc=loadXMLDoc("books.xml"); newatt=xmlDoc.createAttribute("edition"); newatt.nodeValue="first"; x=xmlDoc.getElementsByTagName("title"); x[0].setAttributeNode(newatt); 54 Create an Attribute Using setAttribute()  The setAttribute() method creates a new attribute if the attribute does not exist, it can be used to create a new attribute.  Example xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName('book'); x[0].setAttribute("edition","first"); 55 Create a Text Node  The createTextNode() method creates a new text node:  Example  xmlDoc=loadXMLDoc("books.xml"); newel=xmlDoc.createElement("edition"); newtext=xmlDoc.createTextNode("first"); newel.appendChild(newtext); x=xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newel); 56 Create a CDATA Section Node  The createCDATASection() method creates a new CDATA section node.  Example  xmlDoc=loadXMLDoc("books.xml"); newCDATA=xmlDoc.createCDATASection("Special Offer & Book Sale"); x=xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newCDATA); 57 Create a Comment Node  The createComment() method creates a new comment node.  Example  xmlDoc=loadXMLDoc("books.xml"); newComment=xmlDoc.createComment("Revised March 2008"); x=xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newComment); 58 Add a Node - appendChild()  The appendChild() method adds a child node to an existing node.  The new node is added (appended) after any existing child nodes. Note: Use insertBefore() if the position of the node is important.  Example: creates an element (), and adds it after the last child of the first element: xmlDoc=loadXMLDoc("books.xml"); newel=xmlDoc.createElement("edition"); x=xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newel); 59 Insert a Node - insertBefore()  The insertBefore() method is used to insert a node before a specified child node.  This method is useful when the position of the added node is important:  Example xmlDoc=loadXMLDoc("books.xml"); newNode=xmlDoc.createElement("book"); x=xmlDoc.documentElement; y=xmlDoc.getElementsByTagName("book")[3]; x.insertBefore(newNode,y); 60 Add a New Attribute  There is no method called addAtribute().  The setAttribute() method creates a new attribute if the attribute does not exist:  Example xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName('book'); x[0].setAttribute("edition","first"); 61 Add Text to a Text Node - insertData()  The insertData() method inserts data into an existing text node.  The insertData() method has two parameters:  offset - Where to begin inserting characters (starts at zero)  string - The string to insert  Example: add "Easy" to the text node of the first element of the loaded XML xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("title")[0].childNode s[0]; x.insertData(0,"Easy "); 62 Copy a Node  The cloneNode() method creates a copy of a specified node.  The cloneNode() method has a parameter (true or false). This parameter indicates if the cloned node should include all attributes and child nodes of the original node. 63 Copy a Node  Example: copies the first node and appends it to the root node of the document xmlDoc=loadXMLDoc("books.xml"); oldNode=xmlDoc.getElementsByTagName('book')[0]; newNode=oldNode.cloneNode(true); xmlDoc.documentElement.appendChild(newNode); //Output all titles y=xmlDoc.getElementsByTagName("title"); for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write(" "); } 64 Create an XMLHttpRequest Object  All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.  Syntax for creating an XMLHttpRequest object:  xmlhttp=new XMLHttpRequest(); Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 65 Send a Request To a Server  To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:  xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); Method Description open(method,url,asy nc) Specifies the type of request, the URL, and if the request should be handled asynchronously or not. method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous) send(string) Sends the request off to the server. string: Only used for POST requests 66 GET or
Tài liệu liên quan