As a VB developer, you may have access to the Extensible Markup Language (XML) document. Now you want to process the XML document and integrate it into your solution. You can program and parse it as a common text document, but it is too inefficient to do so without the use of XML's power: it can represent data in a structured manner.
The best way to get information from an XML file is to use the XML parser. A parser is a software that makes data in XML files easy to use. As a VB developer, you may want to get a parser that supports Document Object Model (DOM. Dom describes a series of standard methods for accessing XML and HTML documents. These methods should be implemented by the parser. A parser that supports Dom should convert XML data into a series of objects, so that you can perform secondary programming on these objects. In this article, you will learn how to use the DOM structure implemented by Microsoft Parser (MSXML. dll) to access and maintain the XML document.
As we move on, let's take a look at the XML code to see how this parser makes our life easier. The document CDS. xml below is used to represent each project of a recording. Each project contains information such as lead singer, title, and audio 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> gglad 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 references an external DTD (document type description), which describes the hierarchy and content of a specific type of XML. The XML parser uses DTD to verify the correctness of the XML document. DTD is just one of the ways you can use the parser to verify whether the XML document is legal. Another increasingly popular method is XML schemas, which uses XML to describe schemas rather than DTD. Unlike DTD, schema is described in XML, that is, it uses its own "interesting" syntax.
The following document describes 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 discuss DTD and XML schemas too deeply, XML Schema reference based on XML-DATA has been submitted to W3C.
What is Dom:
The xml dom structure implements the content of an XML document as an object model. W3C Dom Level 1 describes how to implement attributes, methods, and events in the DOM structure. Microsoft's Dom implementation fully supports W3C standards, and there are many new features that make it easier for programs to access XML files.
How to Use dom
To use Dom, you need to create an XML Parser instance. Microsoft has created a series of standard com interfaces in MSXML. DLL to make it possible to create an instance. MSXML. dll contains the Type Library and applicable code, which you can use to process XML files. If you use a client that can implement scripts, such as VBScript and IE, you can use the Createobject method to obtain the parser instance.
Set objparser = Createobject ("Microsoft. xmldom ")
If you use ASP (Active Server Page), you use the server. Createobject method.
Set objparser = server. Createobject ("Microsoft. xmldom ")
If you are using VB, you can create a reference to the MSXML library to access the Dom. To use MSXML in VB6.0, perform the following operations:
Open the project references item
Select Microsoft XML and Version 2.0 from the COM object. If you cannot find this item, you need to get it.
You can create a parser instance.
Dim xdoc as MSXML. domdocument set xdoc = new MSXML. domdocument
You can obtain MSXML. dll in two ways.
You can install ie5.0. The MSXML parser is the integrated component.
Or you can download it from the relevant website.
Once you have created a reference to the type library, you can perform parsing and import the document. In short, you can process the XML document.
You may be confused. What should I do? If you open the MSXML library and use the Visual Basic 6.0 object viewer to view the object model, you will find that it is rich. This article will show you how to use the domdocument class and ixmldomnode interface to access the XML document.
How to load a document:
To import an XML document, you must first create a domdocument instance.
Dim xdoc as MSXML. domdocument
Set xdoc = new MSXML. domdocument
When you get a legal reference, you can use the load method to call a document. The parser can be transferred from the local hard disk or from the network through UNC or URL.
The hard disk is transferred as follows:
If xdoc. Load ("C:/My Documents/CdS. xml") then
'The document has been transferred in.
'Do what we like to do
Else
'Document import failed.
End if
When you finish the work, you need to release this reference. MSXML does not directly implement the close method. You 'd better set it to nothing to close it.
Set xdoc = nothing
When you call a document, it is asynchronous by default. You can modify the async attribute. If you want to operate the document, you must first check the readystate attribute to confirm the state of the document. It will return five possible results.
Status
Attribute Value
Not initialized: the import document has not started
0
Calling: the load method is being executed.
1
Transfer completed: the load method has been completed.
2
Interaction stage: Dom can be read-only checked and partially parsed.
3
Complete: The data is completely parsed and can be read/written. 4
The MSXML parser implements some useful methods. You can use these methods to track the status of the import process when calling a large document. These methods are also helpful for asynchronous import of documents from the Internet.
To open a document on the internet, you must provide an absolute URL and add the http: // prefix. The following is an example.
Xdoc. async = false
If xdoc. Load ("http://www.develop.com/hp/brianr/cds.xml") then
'The document has been transferred in.
'Do what we like to do
Else
'Document import failed.
End if
Set the async attribute to false, so that the parser will not give control to your code before the file is transferred. If you save async as true, you must check the readystate attribute or use the domdocument event to prompt your code when the document is accessible.
Handling error:
Your document may fail to be transferred for various reasons. The most common cause is that the document name provided to the parser is incorrect. Another common cause is that the XML document is invalid.
The default parser will verify whether your document complies with a DTD or schema. You can avoid the parser from performing verification. Before executing the load method, set the domdocument attribute validateonparse to false.
Dim xdoc as MSXML. domdocument
Set xdoc = new MSXML. domdocument
Xdoc. validateonparse = false
If xdoc. Load ("C:/My Documents/CdS. xml") then
'The document has been transferred in.
'Do what we like to do
Else
'Document import failed.
End if
It is not a good idea to disable the verification function beforehand. It will cause many problems, at least it will be the data in the wrong format that you provide to your users.
You can access the parseerror object to obtain information about the error type from the parser. Create an ixmldomparseerror interface reference and point it to the parseerror object of the document. The ixmldomparseerror interface implements seven attributes to give you the cause of the error.
The following example shows a message box listing all the error messages in the parseerror object.
Dim xdoc as MSXML. domdocument
Set xdoc = new MSXML. domdocument
If xdoc. Load ("C:/My Documents/CdS. xml") then
'The document has been transferred in.
'Do what we like to do
Else
'Document import failed.
Dim strerrtext as string
Dim xpe as MSXML. ixmldomparseerror
'Get the parseerror object
Set xpe = xdoc. parseerror
With xpe
Strerrtext = "Your XML document cannot be transferred "&_
"The reason is." & 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
Msgbox strerrtext, vbexclamation
End if
Set xpe = nothing
You can use the parseerror object to report error information to your users, or write it into your log. You can also try to solve the problem yourself.
How to obtain information from XML documents:
Once you have successfully transferred the document, the next step is how to obtain information from it. When you operate a document, you often use the ixmldomnode interface to read/write each separated node element. Before using it, you must first understand the 13 node element types supported by MSXML. Below are the most common types.
Dom Node Type
Example
Node_element
<Artist type = "band"> the offspring </artist>
Node_attribute
Type = "band"> the Offspring
Node_text
The Offspring
Node_processing_instruction
<? XML version = "1.0"?>
Node_document_type
<! Doctype compactdiscs System "CDs. DTD">
You can access the node type through the two attributes implemented on the ixmldomnode interface. The nodetype attribute lists all domnodetype projects (some projects are listed in the table above ). In addition, you can use the nodetypestring attribute to obtain the string representing the node type.
Once you have the DOM reference of the document, you can traverse the node hierarchy. Through document reference, you can access the childnodes attribute, which provides a directory containing all nodes from top to bottom. The childnodes attribute implements ixmldomnodelist. It supports the for/each structure of Visual Basic, so you can list all nodes in childnodes. In addition, the childnodes attribute implements the level attribute, which can return the number of all subnodes.
Not only does the Document Object have the childnodes attribute, but each node has the childnodes attribute. Because of this, the childnodes attribute works with the ixmldomnode's haschildnodes attribute, which makes it very easy to traverse documents, access elements, attributes, and values.
It is worth mentioning that there is a parent-child relationship between elements and element values. For example, in the CDs XML document, the element <title> indicates the name of the song. To know the value of <title>, you need to access the node attribute node_text. If you find that a node has data you are interested in, you can access its attributes, or access its parent node through the parentnode attribute.
How to traverse XML documents:
Nodes that can traverse documents use document objects. Because XML itself is a hierarchical structure, it is easy to write recursive code to access the entire document.
The loaddocument program opens the XML document and calls another program displaynode to display the document structure. Loaddocument is passed to the childnodes attribute of the open XML document as its parameter, and an integer is passed to indicate the level at which the display starts. The Code uses parameters to format the text in the Visual Basic document structure display window.
The function of the displaynode attribute traverses the document to find the required node_text node type string. Once the code finds a node of node_text, it uses the nodevalue attribute to obtain the corresponding text string. In addition, the parentnode attribute of the current node points to an element-type node. The element node implements a nodename attribute,
The nodename and nodevalue attributes are displayed.
If a node has sub-nodes, it will check the haschildnodes attribute to confirm that displaynode will call itself to know all of the traversal documents.
The displaynode program uses Debug. Print to write relevant information to the Visual Basic window.
Public sub loaddocument ()
Dim xdoc as MSXML. domdocument
Set xdoc = new MSXML. domdocument
Xdoc. validateonparse = false
If xdoc. Load ("C:/My Documents/sample. xml") then
'The document loaded successfully.
'Now do something intersting.
Displaynode xdoc. childnodes, 0
Else
'The document failed to load.
'See the previous listing for error information.
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 sub
Displaynode uses the haschildnodes attribute to determine whether to call itself again. You can also use the Level Attribute of the node. If it is greater than 0, a subnode exists.
What to do next:
This is just the beginning. Now you can have a better understanding of XML and Microsoft Parser (MSXML. dll ). You can do something interesting, such as changing the value of a node, searching for documents, and creating your own documents. Visit the msdn online XML Developer Center For more examples, articles, and downloads.
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