DOM experience

zhaozj2021-02-16  44

DOM experience

Frush

This article describes the structure of the DOM (Document Object Model) and the general usage method. Through this article, readers can learn to use DOM to perform common processing on XML documents. This article does not discuss DOM design and implementation skills.

Key words:

XML DOM

Overview

The DOM (Document Object Model) is a description system of XML data, which saves XML data with a document of a tree structure. In addition, the DOM also includes an API that is analyzed and processes XML data.

Before you start using the DOM, you first take a look at its structure. The overall structure on the DOM is a Composite mode. All XML units, whether documents, elements, or attributes, text, is a Node (node) in the DOM. According to the definition of the Composite mode, each Node can contain other NODEs, so it is easy to constitute a tree structure. Lift a simple example, the following XML document

Effective C </ Title></p> <p><Author></p> <p><Name> scott meyers </ name></p> <p><Gender> Male </ gender></p> <p><Nationality> USA </ nationality></p> <p></ Author></p> <p><Publisher> Addison-Wesley </ Publisher></p> <p></ Book></p> <p>This will be like this in the storage form in the DOM:</p> <p>Since I have already learned the structure of the DOM document, I will learn how to operate the DOM documentation. For such a tree structure, more important operations have document generated, document traversal, and the processing of the node content (read, modification, etc.), the operation of the node itself (insert, deletion, replacement, etc.) and the serialization of the document. Below, we will learn these operations one by one.</p> <p>DOM documentation</p> <p>Use the DOM to process XML data, first require the following three steps:</p> <p>1. Create DocumentBuilderFactory. This object will create DocumentBuilder.</p> <p>2. Create DocumentBuilder. DocumentBuilder will parse the input to create a Document object.</p> <p>3. Analyze the input XML and create a Document object.</p> <p>DocumentBuilderFactory is a Singleton, so you can't go directly, you should call DocumentBuilderFactory.newInstance () to get the instance of DocumentBuilderFactory. In addition, DocumentBuilderFactory is also an object factory (you can see from the name), you can use it to create DocumentBuilder.</p> <p>A DocumentBuilder's PARSE method will usually return a document object (need to plug in: Document is just an interface, with javax.xml.parsers.DocumentBuilder's Parse method is actually Org.Apache.crimson.tree.xmldocument object). The PARSE method accepts many input parameters, including File, InputStream, InputSource, String type URI, and more. The Parse method analyzes the input source and generates a DOM tree structure - Document object in memory.</p> <p>The common code of these three steps is as follows:</p> <p>File docfile = new file ("ORDERS.XML");</p> <p>Document Doc = NULL;</p> <p>Try {</p> <p>DocumentBuilderFactory DBF = DocumentBuilderFactory.newinstance ();</p> <p>DocumentBuilder DB = dbf.newdocumentbuilder ();</p> <p>DOC = db.parse (docfile);</p> <p>} catch (exception e) {system.out.print ("Problem Parsing The File.");</p> <p>The PARSE method may throw IOEXCEPTION or SAXEXCEPTION, indicating that the input exception and parsing exception, respectively.</p> <p>Before you create DocumentBuilder, you can set some parameters for DocumentBuilder to adjust it in the behavior when generating Document. Controlable parameters include:</p> <p>l setcoalescing: Determines if the parser converts the CDATA node into text and merges the CDATA node with the text node around it (if appropriate). The default is False.</p> <p>l setXpandentityReferences: Determine if an external entity reference is expanded. If you are True, insert the external data into the document. The default is True.</p> <p>l setIgnoringcomments: Determine if the comment in the file is ignored. The default is False.</p> <p>l SetignoringeElementContentWhitespace: Determine if you ignore the blank in the element content (similar to the way of browser processing HTML). The default is False.</p> <p>l setNamespaceAware: Determine if the parser pays attention to the namespace information. The default is False.</p> <p>l SetValidating: By default, the parser will not verify the document. Set this parameter to True to open the verification.</p> <p>Set the statements of the parameters as follows:</p> <p>DocumentBuilderFactory DBF = DocumentBuilderFactory.newinstance ();</p> <p>DBF.SetValidating (TRUE);</p> <p>DocumentBuilder DB = dbf.newdocumentbuilder ();</p> <p>DOM document traversal</p> <p>The DOM uses Composite mode. The Node class is the base class of all XML units, Element, Attr, Document, etc. are all Node derived classes. Each Node can contain other NODE or to include content in text format. Therefore, the traversal of the DOM document is quite simple.</p> <p>First get the root node of the document. Use the document.getDocumentelement () method to get an Element type object, which is the root node of the document. For an HTML document, the getDocumentelement () method is the <html> node.</p> <p>As long as the root node is obtained, all direct child nodes of the node can be obtained with the node.getchildnodes () method, thereby traversing the entire tree structure. In addition, a node can be judged by the node.haschildnodes () method to obtain the end condition of the traversal algorithm. The return value of the getChildNodes () method is Nodelist object, NodeList has two methods: int getLength () and Node Item (int), you can use these two methods to securely access each element.</p> <p>The above method is depth priority traversal (using iterative algorithm), and one method is a broad-priority traversal algorithm, and the method to be used is GetFirstChild () (get the first child node) and getNextSibling () (get next Brother node). Treatment of elements</p> <p>First of all, you must first understand the concept of "node" and "element": node and elements in the DOM are not equivalent. "Element" refers to the sum of a pair of tags (TAG) and its internal contained string values, such as the following is an element:</p> <p><Country></p> <p>China</p> <p></ Country></p> <p>But it is not a node, but two. The first node is the <country> node, its value is null; the second node is a text node (node ​​name is #text), and its value is "China / N". The text node is the child node of the <country> node.</p> <p>So, when you handle the content of an element, you need two steps:</p> <p>1. Locate nodes representing the element;</p> <p>2. Handling the first child node of the node;</p> <p>As long as you know the name of an element, you can use the Element.GetElementSbyTagName (String Name) to find all nodes that represent the element. The getElementsBytagname method will automatically traverse the entire tree structure and save all the found nodes returned in a nodelist. Since the Tree structure of the DOM is built in memory, this operation will not be too slow. After finding the node, use the node.getfirstchild () method to obtain a text node that represents the element value, you can modify the value of the node with the Node.setNodeValue (String) method.</p> <p>Handling content of other types of nodes</p> <p>If the node to be accessed is the property node (Node.GetNodeType () == Attribute_Node, you can get all the properties in the node via the GetAttributes () method. The GetAttributes method returns a NameDNodeMap type object, which is a name-----value mapping table that can be randomly accessed by the String type name, or sequentially accessed through the INT type sequence number. Att class (attribute node) has getValue () and setValue () two Accessor for accessing the value of the attribute.</p> <p>There are 12 different types of nodes, and the two most commonly used element nodes and attribute nodes are introduced here, and others have to help it. Node has a getNodeType () method that returns a Short type value to determine the true type of an object, which acts as a role of RTTI. Below is the possible return value of the getNodeType () method:</p> <p>Public static final short element_node = 1;</p> <p>Public Static Final Short Attribute_Node = 2;</p> <p>Public static factory short text_node = 3;</p> <p>Public Static Final Short CData_section_node = 4;</p> <p>Public static final short entity_reference_node = 5; public static factory short entity_node = 6;</p> <p>Public Static Final Short processing_instruction_node = 7;</p> <p>Public static final short comment_node = 8;</p> <p>Public static factory short document_node = 9;</p> <p>Public static factory short document_type_node = 10;</p> <p>Public static factory short document_fragment_node = 11;</p> <p>Public Static Final Short Notation_Node = 12;</p> <p>Node processing</p> <p>For tree data structures, common node processing is the insertion, deletion, and replacement of nodes. DOM provides very easy to use APIs for these operations.</p> <p>Node can be inserted Node.appendChild (Node), can also be used Node.insertBefore (Node newChild, Node refChild); remove nodes can Node.removeChild (Node oldChild); replacement node can Node.replaceChild (Node newChild, Node oldChild ). The DOM will automatically adjust the tree structure, delete, and replace the Oldchild node, which is very convenient.</p> <p>Document is also a node (Node), so you can also insert the node directly into the document. However, pay attention: Only the node created by the document can be inserted into the document, otherwise the WRONG_Document_err exception will be triggered. Create a node using the Document.createxxxx method. You can clone a node with a ClonEnode (Boolean Deep) method, determine if the depth copy is determined by the Boolean type parameter, but the cloned node cannot insert another document. In addition, you can introduce nodes in other documents with Document.ImportNode (Node ImportedNode, Boolean Deep).</p> <p>When you need to process the properties of the element, you can insert the properties with Element.SetaTributenode (Attr Newattr), using Element.RemoveAttribute (String Name) to delete unwanted properties. If the attribute has the same name, you can use Element. RemoveAttributeNode (Attr Oldattr) to specify a deletion of an attribute node.</p> <p>Serialization of documents</p> <p>Each ELEMENT covers the TSTRING method, so as long as a one of the Element is specified as the root, then call its toString method, it will recursively get the entire tree structure under which it is converted into String type objects. As long as this String type object is output to the specified device, you can get an XML document, which is very convenient. The following code will generate a new HTML document (HTML can be said to be a subset of XML) and output on the standard output device.</p> <p>Document newdoc = null;</p> <p>Try {</p> <p>DocumentBuilderFactory DBF = DocumentBuilderFactory.newinstance (); DocumentBuilder DB = dbf.newdocumentbuilder ();</p> <p>NewDoc = db.newdocument ();</p> <p>} catch (exception e) {};</p> <p>Element head = newdoc.createElement ("HEAD");</p> <p>ELEMENT TITLE = NewDoc.createElement ("Title");</p> <p>Title.Appendchild (NewDoc.createTextNode ("Document Created By Dom");</p> <p>Head.Appendchild (title);</p> <p>Element body = newdoc.createElement ("body");</p> <p>Body.Appendchild (NewDoc.createTextNode ("this is a test document");</p> <p>Element newroot = newdoc.createElement ("html");</p> <p>NEWROOT.APPENDCHILD (BODY);</p> <p>Newroot.insertbefore (Head, Body);</p> <p>NewDoc.Appendchild (newroot);</p> <p>System.out.println (newroot);</p> <p>to sum up</p> <p>The DOM generates a tree structure in memory to process XML data, which has an advantage in processing speed and convenience, but the storage space is consumed. If the XML document is relatively large, the resolution process may take a longer time.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-26298.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="26298" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.042</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'PxJrdw92B4lHPkajJZOeplNTn720ebRGxDbzbmYNy6jU_2B_2Bs3zoLDUpNV6CH0T2W6IZFdIy6lC9fwqw0JqP_2FQEA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>