XML DOM Getting Started Guide

zhaozj2021-02-16  71

XML DOM Getting Started Guide

BRIAN RandellDevelopmentor 1999 Abstract: This article discusses how to access and operate XML documents by performing XML DOM after XML document is revealed by Microsoft (R) XML Parser. (10 pages) What is the exact definition of DOM? How to use XML DOM? How to load a document? How to retrieve information in the XML document How to move back and forth in the document? What are you doing now? Preface If you are Visual Basic (R) developers, you receive some "Scalable Markup Language (XML)" document format data. At this point you must have to get information in the XML document and combine these data into the Visual Basic solution. You will inevitably write code to analyze the contents of the XML file, which is just a text file. But this is no longer a good way to make a good way, and erased the advantages of XML: the structure of the data. The preferred method of retrieving the information in the XML file is to use the XML analysis program. It is very simple, the XML analysis program is a software, it reads the XML file and makes the data available. As a developer of Visual Basic, you want to use an Analysis program that supports XML Document Object Model (DOM) ". The DOM defines the standard command set that the analyst should be revealed so that you can access HTML and XML document content in the program. Supporting the DOM's XML analysis program Remove the data in the XML document and exposes it through a group of objects to which it can be programmed. In this article, you will learn how to access and operate it (msxml.dll) by performing XML DOM after the XML document is revealed by Microsoft (R) XML Parser. Before reading, you should look at the original XML file so that you can make your life more easily and have a concept. The following code reveals the contents of the file CDS.xml containing the compressed disk item. Each item contains information such as artists, titles and tracks.

Frank sinatra in The Wee Small Hours </ Title> <TRACKS> <Track> in The Wee Small Hours </ track> <track> Mood Indigo </ track> <track> Glad to be unhappy </ track> <track> i Get Along Without You Very Well </ track> </ tracks> <price> $ 12.99 <compactdisc> <artist type = "band"> the offspring </ artist> <title numberoftracks = "5"> Americana < / Title> <tracks> <track> Welcome </ track> <track> have you ever </ track> <track> staring at the sun </ track> <track> pretty fly (for a white guy) </ track> </ tracks> <price> $ 12.99 </ price> </ compactdisc> </ compactdiscs> The second row of the above documents involves the external DTD, or called the "Document Type Definition" file. DTD defines the layout and expected content of a particular type of XML document. The XML analysis program can use DTD to determine if the document is valid. DTD is just a way to use it helps analyze the program verification document. There is also an increasingly popular verification document to "XML architecture". Unlike DTD, we use XML definition schema, while DTD uses them "interesting" syntax. The following code shows the contents of cds.dtd used by cds.xml: <! Element compactdiscs (compactdisc *)> <! Element CompactDisc (Artist, Title, TRACKS, Price)> <! Entity% Type "Individual | Band"> <! Element Artist (#pcdata)> <! Attlistraft type (% type;) #Required> <! Element Title (#pcdata)> <! Attlist title number uBEROFTRACKS CDATA #Required> <! Element TRACKS (TRACK *)> < ! Element Price (#pcdata)> <! Element TRACK (#pcdata)> This article is not intended to explore DTD and "XML architecture" in depth.</p> <p>XML Architecture Language (English) is based on XML data (English) annotation (in accordance with W3C). What is the exact definition of DOM? XML's DOM is an object model that reveals the content of the XML document. W3C's Document Object Model (DOM) Level 1 specification typically defines that DOM should reveal why attributes, methods, and events. Microsoft's DOM execution method fully supports W3C standards, and some of its other features are more convenient to use XML files in the program. How to use XML DOM? Use XML DOM by creating an instance of an XML analysis program. To this end, Microsoft reveals XML DOM through a set of standard COM interfaces in MSXml.dll. Msxml.dll contains class libraries and execution code used when using XML documents. If you are using a script, such as VBScript in Internet Explorer, use the DOM by creating an instance of an analyte object with the CreateObject method. Set objParser = CreateObject ("Microsoft.xmLDom")</p> <p>If you are using VBScript from Active Server Page (ASP), you should use Server.createObject.</p> <p>Set objParser = Server.createObject ("Microsoft.xmldom")</p> <p>If you are using Visual Basic, you can access the DOM by setting a reference to the MSXML class library (provided in msxml.dll). Steps to use MSXML within Visual Basic 6.0:</p> <p>Open the engineering reference dialog. Select Microsoft XML, V2.0 from the list of available COM objects. If this item is not found, you must first get the MSXML class library. At this time, you can create an analyte object instance. Dim xdoc as msxml.domdocumentset xdoc = new msxml.domDocument</p> <p>Where can I find msxml.dll? There are two ways to get the MSXML class library:</p> <p>The Internet Explorer 5.0- MSXML analysis program can be installed is a complete component. Another way is to download the reproducible Microsoft XML Parser version.</p> <p>After reference to the class library in the Visual Basic project, you can call the analyst, load your document, and use the data in the document.</p> <p>Maybe you are puzzling now - what I am using now? If you open the MSXML class, use the Visual Basic 6.0 object browser to check its object model, you will find that the object model is so rich. This article demonstrates how to use the DomDocument class and the IXMLDomnode interface to access the XML document.</p> <p>Figure 1. MSXML Analysis Program Object Model</p> <p>How to load a document?</p> <p>To load an XML document, you must first create an instance of the DomDocument class:</p> <p>Dim xdoc as msxml.domdocument set xdoc = new msxml.domdocument</p> <p>After obtaining a valid reference, use a load method to open the file. The MSXML analysis program can load an XML document from the local disk, and use the UNC to use the URL to load the document.</p> <p>To load a document from disk, create the following constructor using the load method:</p> <p>If Xdoc.Load ("c: / my documents / cds.xml") The 'document is loaded. 'Do something interesting now. Else 'document loading is unsuccessful. After the endiff is used up the document, you need to release your object reference to it. The MSXML analysis program does not reveal clearly. The best way is to explicitly set the reference to Nothing.</p> <p>Set xdoc = Nothing</p> <p>When the analysis program is required to load files, it is not synchronously by default. Change the Boolean Async property of this document can change this feature. It is important to check the ReadyState property of the document, and ensure that the document is ready before starting to check its content. The value of the readyState property may return is one of the following five:</p> <p>The status value has not been initialized: the loading has not yet begun. 0 Loading: Loading method is being executed. 1 has been loaded: The load method has been completed. 2 Interaction: There is enough DOM available for read-only check, and the data is only partially analyzed. 3 Complete: Data has been loaded and analyzed and can be used to read / write operations. 4</p> <p>The MSXML analysis program reveals events that track the status of the load process when loading large documents. These events are also useful when loading documents from the URL on the Internet.</p> <p>To open a file from the URL, use the full format of the URL to specify the location of the file. You must add an HTTP: // prefix in front of the file location.</p> <p>Here is an example of loading a file from a URL:</p> <p>Xdoc.async = false if xdoc.load ("http://www.develop.com/hp/brianr/cds.xml") The 'document loading is successful. 'Do something interesting now. Else 'document loading is unsuccessful. END IF</p> <p>Set the Async property of the document to false, the analyst does not return the control to your code before the document is fully loaded and can operate. If you set it to True, you must check your readyState property before accessing the document, or use DomDocument's event, inform you the code.</p> <p>Handle</p> <p>During the various reasons, document loading is likely to fail. The most common cause may be invalid that the document name transmitted to the load method is invalid. Another reason may be that the XML document itself is invalid.</p> <p>By default, the MSXML analysis program verifies whether DTD or architecture is specified in your document. If the ValidateonParse property referenced by the DomDocument object is set before calling the load method, the analyst does not verify the document.</p> <p>Dim xdoc as msxml.domdocument set xdoc = new msxml.domdocument xdoc.validateonParse = false if xdoc.load ("c: / my documents / cds.xml") The 'document loading is successful. 'Do something interesting now. Else 'document loading is unsuccessful. END IF</p> <p>However, warning you in advance: The authentication feature of the closing the analysis program is not a good way to make an application. Incorrect documents have failed to cause various reasons. At least, it provides users with invalid data.</p> <p>Regardless of the type of fault, you can request the analyst to provide fault information by accessing the ParseError object. To use the properties of the ParseError object, set the reference to the IXMLDompivalSeerror interface of the document. The IxmlDompivalSeError interface reveals that 7 properties can be used to study the cause of the error.</p> <p>The following example shows a message box and all error messages given by the ParseError object.</p> <p>Dim xdoc as msxml.domdocument set xdoc = new msxml.domdocument if xdoc.load ("c: / my documents / cds.xml") The 'document is successfully loaded. 'Do something interesting now. Else 'document loading is unsuccessful. Dim strErrText As String Dim xPE As MSXML.IXMLDOMParseError 'get ParseError objects Set xPE = xDoc.parseError With xPE strErrText = "Your XML Document failed to load" & _ & vbCrLf & _ "Error #:" "due the following error." & .rrorcode & ":" & xpe.reason & _ "line #:" & .line & vbcrf & _ "line position:" & .linepos & vbrlf & _ "Position in file:" & .filepos & vbrlf) "Source Text:" & .SrcText & Vbcrlf & _ "Document URL:" & .url End with Msgbox Strerrtext, Vbexclamation End If Set Xpe = Nothing You can use the ParseError object to expose information, display this information to the user, record it to In the error file, or try to correct the error.</p> <p>Retrieve information in XML documentation</p> <p>After loading the document, the next step is to retrieve information from the document. Although document objects are important, they can still be found that in most time is using the ixmldomnode interface. Use the ixmldomnode interface to read and write separate node elements. Before doing anything, you must understand the 13 node types that MSXML analysis programs usually support. The following table lists several most commonly met the node type.</p> <p>DOM Node type instances NODE_ELEMENT <artist type = "band"> Offspring </ artist> NODE_ATTRIBUTE <artist type = "band"> Offspring </ artist> NODE_TEXT <artist type = "band"> Offspring </ artist> NODE_PROCESSING_INSTRUCTION <? Xml Version = "1.0"?> node_document_type <! doctype CompactDiscs System "CDS.DTD"></p> <p>The node type is accessed through the two properties exposed by the ixmldomnode interface. The NodeType property reveals the enumeration of the DomNodeType project (some of which have been included in the table above). In addition, you can also use nodetypeString to retrieve the text string of the node type.</p> <p>When there is a reference to the document, you can start moving back and forth in the hierarchy of the node. From your document reference, you can access the ChildNodes property that provides all the nodes in the document from the top of the document. The ChildNodes property reveals IXMLDomnodeList, which supports Visual Basic for / Each configuration. Therefore, you can enumerate all a single node for the ChildNodes property. In addition, the ChildNodes property reveals the Level property, which can return the number of existing child nodes. The document object not only reveals the ChildNodes property, but also reveals all a single node. In this way, the HaschildNodes property of ixmldomnode is combined, so that the elements, attributes, and values ​​are checked back and forth in the node level. It is very simple.</p> <p>One thing that needs to be reminded is that the primary relationship between document elements and element values. For example, in a CD XML document, the element <title> shows a title of a song. To retrieve the actual value of the <title> element, you need to look for node_text type nodes. Once you find the node with interest data, you can check the properties, even through the ParentNode property to reach and access its primary node.</p> <p>How to move back and forth in the document?</p> <p>In the XML document, you can move back and forth in a node that is revealed by the document object. Because the XML document is hierarchical, the recursive routine written back and forth in the entire document is relatively easy.</p> <p>The LoadDocument routine opens an XML document. The loadDocument then calls another routine DisplayNode, which is really moving back and forth in the document. LoadDocument will reference the ChildNodes property that is passed as parameters and integer values ​​to the current open XML document, specifies where to start regenerating levels. The code uses a constant parameter to format the display of text in the Visual Basic "Quick Window" of the document structure.</p> <p>The DisplayNode function is moved back and forth in the document and looks for node-specific node_text types. When the code finds the node_text type node, it retrieves the text of the node with the NodeValue property. In addition, the ParentNode property of the current node is used to get the backtrack reference of the Node_Element type node. Node_element type node reveals the NodeName property. The content of NodeName and NodeValue is displayed.</p> <p>If the HaschildNodes property is checked, it is determined that the node has a child node, then DisplayNode recursives itself until it reaches the end of the document.</p> <p>The displayNode routine uses Debug.print to write the information to the "Quick Window" of Visual Basic:</p> <p>Public Sub loadDocument () DIM xdoc as msxml.domdocument set xdoc = new msxml.domdocument xdoc.validateonparse = false if xdoc.load ("c: / my documents / sample.xml") The 'document loading is successful. 'Do something interesting now. DisplayNode XDoc.childNodes, 0 else 'document loading is unsuccessful. 'View the error message listed above. End If End Sub Public Sub DisplayNode (ByRef Nodes As MSXML.IXMLDOMNodeList, _ ByVal Indent As Integer) Dim xNode As MSXML.IXMLDOMNode Indent = Indent 2 For Each xNode In Nodes If xNode.nodeType = NODE_TEXT Then Debug.Print Space $ ( indent) & xNode.parentNode.nodeName & _ ":" & xNode.nodeValue End if if xNode.hasChildNodes then DisplayNode xNode.childNodes, indent End if Next xNode End SubDisplayNode with HasChildNodes property to determine whether it should re-call its own. You should also use the LEVEL attribute of the node and check the value greater than 0.</p> <p>What are you doing now?</p> <p>This article is only used as a entry. Now you can learn in depth, enhance the understanding of the XML and MSXML analysis programs. You can do a lot of interesting things, such as updating the value of the independent node item, search in the document, create your own document, and so on. If you need more instances, articles, and downloads, visit the MSDN Online XML Developer Center.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-15597.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="15597" 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.037</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 = '3ZNXKWouzW98kg0X6VgqaRhP5e72OH_2BsEEPM4r5_2FRKE4aEnQxDt5jNwCEwPoRslfrvMHYekrCuS9mvSeFoS4YA_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>