Xml dom Getting Started Guide

Source: Internet
Author: User
Tags xml parser

Abstract:This article discusses how to access and operate XML documents by executing the xml dom after the XML document is exposed by Microsoft (r) XML parser. (10 pages in total)

Directory

Preface
What is the exact definition of Dom?
How to use xml dom?
How to load documents?
Troubleshooting
Retrieve Information in XML documents
How to move back and forth in the document?
What do we do now?

If you are a visual basic (r) developer, you receive some data in the "Extensible Markup Language (XML)" document format. In this case, you must obtain the information in the XML document and combine the data into the visual basic solution. You must write your own code to analyze the content of an XML file, which is just a text file. However, this is by no means a fast and cost-effective method. In addition, it can erase the advantages of XML: structured methods for displaying data.

A better way to retrieve information in an XML file is to use an XML analysis program. XML analytics is a software program that reads XML files and makes the data available. As a Visual Basic developer, you want to use an analytic program that supports the XML "Document Object Model (DOM. Dom defines a standard set of commands that should be exposed by the analysis program, allowing you to access HTML and XML document content in the program. The XML analysis program that supports Dom extracts data from XML documents and exposes it through a set of objects that can be programmed. In this article, you will learn how to access and operate on an XML file (MSXML. dll) after the XML file is exposed by Microsoft (r) XML parser ).

Before reading it, you should take a look at the original XML file to understand how the analytic program makes your life easier. The following code exposes the content of the file CDs. xml containing the compressed Disk Project. Each item contains information such as artist, title, and track.

<?xml version="1.0"?> <!DOCTYPE compactdiscs SYSTEM "cds.dtd"> <compactdiscs> <compactdisc> <artist type="individual">Frank Sinatra</artist> <title numberoftracks="4">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</price> </compactdisc> <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 line of the above document involves an external DTD, or a document type definition file. DTD defines the layout and expected content of specific types of XML documents. The XML analysis program can use DTD to determine whether the document is valid. DTD is only one method that can be used to help the analysis program verify the document. There is also an increasingly popular method for verifying documents: "XML architecture ". Unlike DTD, we use XML to define the architecture, while DTD uses their own "interesting" syntax.

The following code shows the content of the CDs. DTD used by CDs. xml:

<!ELEMENT compactdiscs (compactdisc*)> <!ELEMENT compactdisc (artist, title, tracks, price)> <!ENTITY % Type "individual | band"> <!ELEMENT artist (#PCDATA)> <!ATTLIST artist type (%Type;) #REQUIRED> <!ELEMENT title (#PCDATA)> <!ATTLIST title numberoftracks CDATA #REQUIRED> <!ELEMENT tracks (track*)> <!ELEMENT price (#PCDATA)> <!ELEMENT track (#PCDATA)> 

This article does not intend to go into the DTD and "XML architecture" in depth ". The XML architecture language (English) is based on XML data (English) annotations (W3C.

Xml dom is an object model that exposes the content of an XML document. W3CDocument Object Model (DOM) Level 1 SpecificationThe Dom usually defines why attributes, methods, and events should be exposed. Microsoft's Dom execution method fully supports W3C standards. Some of its other features make it easier to use XML files in programs.

Use the xml dom by creating an XML analysis program instance. To this end, Microsoft exposes the xml dom through a set of standard com interfaces in MSXML. dll. MSXML. dll contains the class libraries and Execution code used to use XML documents. If you are using a client program with scripts, such as VBScript in Internet ExplorerCreateobjectMethod CreationAnalytic programObject instance to use the Dom.

Set objparser = Createobject ("Microsoft. xmldom ")

If you are using VBScript from Active Server Page (ASP), you should useServer. Createobject.

Set objparser = server. Createobject ("Microsoft. xmldom ")

If you are using Visual Basic, you can access the DOM by setting references to the MSXML class library (provided in MSXML. dll. To use MSXML in Visual Basic 6.0, follow these steps:

  1. OpenEngineering referenceDialog box.
  2. Select from the list of available COM objectsMicrosoft XML, V2.0. If this item is not found, you must first obtain the MSXML class library.
  3. You can createAnalytic programObject instance.

    Dim xdoc as MSXML. domdocument
    Set xdoc = new MSXML. domdocument

Where can MSXML. dll be found? There are two methods to obtain the MSXML Class Library:

  • You can install the Internet Explorer 5.0-MSXML analytics program as a complete component.
  • Another way is to download the reusable Microsoft XML Parser version.

After referencing the class library in the Visual Basic Project, you can call the analysis program, load the document, and use the data in the document.

Maybe you are wondering-; What Am I using now? If you open the MSXML class library and check its object model with the Visual Basic 6.0 Object Browser, you will find that the object model is so rich. This article demonstrates how to useDomdocumentClass andIxmldomnodeInterface to access the XML document.

Figure 1. MSXML analysis program Object Model

How to load documents?

To load XML documents, you must first createDomdocumentClass instance:

Dim xDoc As MSXML.DOMDocument Set xDoc = New MSXML.DOMDocument 

After obtaining a valid reference, useLoadMethod to open the file. The MSXML analytics program can load XML documents from a local disk. On the internet, it uses UNC reference or URL to load documents.

To load documents from a disk, useLoadMethod to create the following structure:

If xdoc. Load ("C:/My Documents/CdS. xml") then' file is loaded successfully. 'Do something interesting now. Else' document loading failed. End if

After using this document, you need to release your object reference to it. MSXML analysis programs are not explicitCloseMethod. The best way is to explicitly set the referenceNothing.

Set xDoc = Nothing 

When the analysis program is required to load files, it is not executed synchronously by default. Change the Boolean value of this documentAsyncThis attribute can be changed. It is important to check the documentReadystateAttribute to ensure that the document is ready before it starts to check its content.ReadystateThe attribute may return one of the following values:

Brian Randell
Developmentor
October 1999

Xml dom Getting Started Guide PrefaceWhat is the exact definition of Dom?How to use xml dom?
Status Value
Not initialized: loading has not started yet. 0
Loading: The loading method is being executed. 1
Loaded: The loading method has been completed. 2
Interaction: there is sufficient Dom available for read-only checks, and data is only partially analyzed. 3
Complete: the data has been loaded and analyzed and can be used for read/write operations. 4

The MSXML analysis program shows events that can track the loading process status when loading large documents. These events are also useful when documents are not synchronously loaded from URLs on the Internet.

To open a file from a URL, use a complete URL to specify the file location. You must add the http: // prefix before the file location.

Here is an example of loading a file from a URL:

Xdoc. async = false if xdoc. Load ("http://www.develop.com/hp/brianr/cds.xml") then' file loaded successfully. 'Do something interesting now. Else' document loading failed. End if

AsyncSet propertyFalseThe analysis program does not return the control to your code until the document is fully loaded and can be operated on. If you set itTrueYou must checkReadystateAttribute, or useDomdocumentTo inform your code when the document is ready.

Troubleshooting

Document loading may fail due to various reasons. The most common cause may be the transferLoadThe document name of the method is invalid. Another reason may be that the XML document itself is invalid.

By default, MSXML analytics verifies whether a DTD or architecture is specified in your document. IfLoadMethodDomdocumentObject ReferenceValidateonparseAttribute, so that the analysis program does not verify the document.

Dim xdoc as MSXML. domdocument set xdoc = new MSXML. domdocument xdoc. validateonparse = false if xdoc. load ("C:/My Documents ents/CDs. XML ") then' file loaded successfully. 'Do something interesting now. Else' document loading failed. End if

However, it is not a good method to disable the verification feature of the analytics when creating an application. Incorrect documentation causes program failure for various reasons. At least, it will provide invalid data to users.

Regardless of the fault type, you can accessParseerrorObject, requiring the analysis program to provide you with fault information. To useParseerrorAttribute of the object. Set the reference toIxmldomparseerrorInterface.IxmldomparseerrorSeven properties are displayed on the page, which can be used to investigate the cause of the error.

The following example shows a message box andParseerrorAll error messages provided by the object.

Dim xdoc as MSXML. domdocument set xdoc = new MSXML. domdocument if xdoc. Load ("C:/My Documents/CdS. xml") then' file loaded successfully. 'Do something interesting now. Else' document loading failed. Dim strerrtext as string dim xpe as MSXML. ixmldomparseerror 'get the parseerror object set xpe = xdoc. parseerror with xpe strerrtext = "Your XML document failed to load" & _ "due the following error. "& vbcrlf & _" Error #:"&. errorcode & ":" & xpe. reason & _ "line #:"&. line & vbcrlf & _ "line position :"&. linepos & vbcrlf & _ "position in file :"&. filepos & vbcrlf & _ "Source Text :"&. srctext & vbcrlf & _ "document URL :"&. URL end with msgbox strerrtext, vbexclamation end if set xpe = nothing

AvailableParseerrorThe information exposed by the object, which is displayed to the user, recorded in the error file, or corrected by yourself.

Retrieve Information in XML documents

After the document is loaded, the next step is to retrieve information from the document. Although the document object is important, it can still be found that it is used most of the time.IxmldomnodeInterface. ExploitationIxmldomnodeInterface to read and write individual node elements. Before doing anything, you must understand the 13 common node types supported by the MSXML analytics. The following table lists the most common node types.

Dom Node Type Instance
Node_element <ArtistType = "band"> offspring </Artist>
Node_attribute <ArtistType="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">

PassIxmldomnodeInterface to access the node type.NodetypeProperty exposedDomnodetypeProject enumeration (some of them are included in the above table ). In addition, you can also useNodetypestringTo retrieve the node-type text string.

After a document is referenced, you can start to move back and forth at the node level. You can accessChildnodesAttribute, which provides a top-down entry to all nodes in the document.ChildnodesProperty exposedIxmldomnodelistIt supports Visual Basic for/each construction. Therefore, you can enumerateChildnodesAll single nodes of the attribute. In addition,ChildnodesAttribute exposureLevelAttribute, which returns the number of existing subnodes.

Document objects are not only exposedChildnodesAttribute, and all individual nodes are displayed. In this wayIxmldomnodeOfHaschildnodesCombining attributes makes it easy to move back and forth at the node level to check elements, attributes, and values.

One thing to be reminded is the master-slave relationship between document elements and element values. For example, in the cd xml document<Title>Reveals the title of a song. To search<Title>The actual value of the element. You need to find the node of the node_text type. After finding a node with data of interest, you can check the attributes or evenParentnodeProperty arrives and accesses its master node.

How to move back and forth in the document?

In XML documents, you can move back and forth between a group of nodes exposed by document objects. Because XML documents are inherently hierarchical, it is easier to write recursive routines that move back and forth throughout the document.

LoaddocumentRoutine to open the XML document. ThenLoaddocumentCall another routineDisplaynodeIt is actually moving back and forth in the document.LoaddocumentPass the reference as a parameter and an integer toChildnodesAttribute to specify where to scale down. The Code uses the contraction parameter to format the text display in the Visual Basic "quick window" in the document structure.

DisplaynodeThe function moves back and forth in the document to find nodes specific to the node_text type. After the code finds a node of the node_text type, it usesNodevalueAttribute to retrieve the text of the node. In additionParentnodeThis attribute is used to obtain the trace reference of node_element nodes. Node_element nodes are exposed.NodenameAttribute.NodenameAndNodevalueIs displayed.

If you pass the checkHaschildnodesAttribute. If the node has a subnodeDisplaynodeCall itself recursively until it reaches the end of the document.

DisplaynodeRoutineDebug. PrintWrite the information to "quick window" in Visual Basic ":

Public sub loaddocument () dim xdoc as MSXML. domdocument set xdoc = new MSXML. domdocument xdoc. validateonparse = false if xdoc. load ("C:/My Documents ents/sample. XML ") then' file loaded successfully. 'Do something interesting now. Displaynode xdoc. childnodes, 0 else' file loading failed. 'View the error information 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 xnode. haschildnodes then displaynode xnode. childnodes, indent end if next xnode end sub

DisplaynodeUseHaschildnodesAttribute to determine whether it should call itself. You should also useLevelAttribute and check the value greater than 0.

What do we do now?

This article is only used for entry. Now you can learn more about XML and MSXML analysis programs. You can do many interesting things, such as updating the value of an independent node item, searching in the document, and creating your own document. For more instances, articles, and downloads, visit the msdn online XML Developer Center.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.