Use VisualBasic to operate XML data

Source: Internet
Author: User
Tags configuration settings xml attribute xsl
What is XML

XML is a simple data storage language that uses a series of simple tags to describe data. These tags can be conveniently created, although XML occupies more space than binary data, XML is extremely easy to master and use.

Different from databases such as access, Oracle, and SQL Server, XML provides powerful data storage and analysis capabilities, such as data indexing, sorting, searching, and consistency, XML only displays data. In fact, the biggest difference between XML and other data forms is that it is extremely simple. This is an advantage that looks a little refined, but it makes XML different.

The simplicity of XML makes it easy to read and write data in any application, which makes XML quickly the only public language for data exchange. Although different application software also supports other data exchange formats, but soon they will support XML, which means that the program can be more easily combined with information generated on Windows, Mac OS, Linux, and other platforms, then it is easy to load XML data into the program, analyze it, and output the results in XML format.

XML advantages

We talked about the fact that XML is longer than exchanging data between different applications, and XML files facilitate the construction of small databases. Not long ago, software used INI files to store configuration information, user parameters, and other information, later, Microsoft introduced the system registry, which was followed by Microsoft's instructions that we should not use the INI file again. Since then, Visual Basic's support for the INI file has been weakened. Unfortunately, the Registry has several fatal disadvantages: it is not a simple text file, it is difficult to read and write, it may become very large and slow, and if the registry somehow fails, it may cause the system to crash.

Placing configuration information in an XML file can avoid these problems. You can even set an XML file as a shared file so that users on different computers can share data, this is incomparable to the Registry.

In ASP. NET, which is called the next-generation ASP, XML can be directly used in Web pages. You can use the data binding control to directly bind data and automatically display it.

Of course, you can also choose not to select XML. You can use text files, registries, and databases to complete the tasks that XML can accomplish. XML is just another tool for data storage and recovery.

XML syntax

The syntax of XML is very simple. XML documents consist of nodes and use the open and close node description tags. The format is very similar to that of HTML tags. The biggest difference between them is: the tag name can be freely defined in XML. For example, the following mark describes a phone number:

<Phone> 987-654-3210 </Phone>

You do not need to declare a tag name.

The start and end tags must be the same. XML is case-sensitive, so the tags must be the same. For example, in the above example, the <Phone> mark must start with the </Phone> mark, but not </phone> or </PHONE>

The node tag can contain attributes. For example, in the following code, the Phone node contains the attribute Type and its value is WorkFax:

<Phone Type = "WorkFax"> 987-654-3210 <Phone>

If you do not want to include a value in a node, you do not need to end the tag. You can add a diagonal line after the start tag to end the node. In the following example, the Number attribute of the Phone tag stores a Phone Number, so you do not need an end tag:

<Phone Type = "WorkFax" Number = "987-654-3210"/>

The structure of the XML document is a tree-like hierarchical structure. The document must have a unique root node, which contains all other nodes. The following is a complete example:

<Addresses>
<Entry Type = "Personal">
<FirstName> Andy </FirstName>
<LastName> Fickle </LastName>
<Street> 1234 Programmer Place </Street>
<City> bugville </City>
<State> CO </State>
<Zip> 82379 </Zip>
<Phone Type = "Home"> 354-493-9489 </Phone>
</Entry>
<Entry Type = "Work">
<FirstName> Betty </FirstName>
<LastName> Masterson </LastName>
<Phone Type = "Work"> 937-878-4958 </Phone>
<Phone type = "workfax"> 937-878-4900 </phone>
</Entry>
...
</Addresses>

Note that similar nodes do not need to contain the same information. For example, the first Entry node contains the address information and home phone number, and the second Entry node contains the Work and WorkFax phone numbers, it does not contain the information contained in the first Entry node.
XML Tool

As shown in the previous example, the XML syntax is so simple that you can make an XML parser in a short time. Fortunately, you don't have to do this, because the XML tool can run on various platforms, including Windows with Visual Basic installed.

It is these L tools that make XML more powerful and complex than XML itself. Different Resolvers allow you to load the entire XML document or only a node at a certain time. In contrast, XML Writer can create an XML document and node at the same time.

The Dom parser allows us to easily load, copy, sort, modify, and store XML files, traverse nodes to obtain names or attributes, and sort the results. Although their functions are not really powerful in relational databases, these features of Dom are still very useful.

XSD can define the format of XML documents. The XSL extension style sheet defines how to convert XML documents to other file formats that can be viewed in Web browsers, such as HTML files.

These tools are actually more complex than XML itself, so all the books that explain XML have spent a lot of time explaining these XML tools. However, this is beyond the scope of this article. Interested readers can refer to the relevant materials.

Visual Basic. NET provides a complete tool for using XML, XSL, and other XML tools. However, you don't have to wait for VB. NET. Microsoft XML Core Service (MSXML) Version 4.0 provides a tool to load and store XML documents from Visual Basic6.0.

Download the latest version of msxmlin msdn.microsoft.com/xml/default.aspand install it on the computer. Using Microsoft XML v4.0 in Visual Basic 6.0 is similar to referencing other objects. First, select the reference menu item in the project menu, select Microsoft v4.0, and click OK, now, you can add an XML object to the VB Application.

Domdocument class

The Document Object Model (DOM) uses a series of corresponding objects to describe the hierarchical state of XML documents. The domdocument class is an MSXML class that depicts the DOM structure of XML documents.

The domdocument class only provides a few useful attributes and methods. The load method loads an XML file. The loadxml method adds a string to an object as XML data. For example, the following code adds a small XML file to the document named xml_document.

Dim xml_document as new domdocument

Xml_document.loadxml _
"<Person>" & vbcrlf &_
"<Firstname> rod </firstname>" & vbcrlf &_
"<Lastname> Stephen </lastname>" & vbcrlf &_
"</Person>"

The XML Attribute of domdocument returns the XML Description of the document. It can display the returned values to see what these documents look like and store them as a file, but this is completely unnecessary, because the Save method of the domdocument object has automatically stored them.

The documentElement attribute of the DOMDocument object indicates the root node of the document data. Generally, the operation of XML documents starts from here.

DOMDocument provides several methods to create a new node. The CreateElement method creates a new element node for the document. Other methods for creating nodes include createAttribute, createProcessingInstruction, and createTextNode, which will not be described here.

IXMLDOMNode class

The IXMLDOMNode class describes a node that provides a series of attributes and methods for searching and manipulating XML documents.
The selectSingleNode method is used to search for the descendant of a specified node. The language used to search for a specified Node path is called XPATH. XPATH is very tricky. This article will not detail its specifications. Next we will introduce two very useful and simple methods for searching subnodes.

Enter the name of the subnode in the selectsingleNode method. This method performs exact search on the subnode of the node. If ". //" is added before the input string, all nodes are searched.

''Search for a child node named "lastname ."
Set last_name_node = address_node.selectsinglenode ("lastname ")

''Search for any descendant named "lastname ."
Set last_name_node = address_node.selectsinglenode (". // lastname ")

The following lists some of the useful attributes of the IXMLDOMNode object:

Attributes. node Attribute Set

NodeName. node Tag Name

NodeTypeString. Node Type

OwnerDocument. Return the node contained in the DOMDocument object

Text. indicates the text content contained in the node. If the node contains other nodes, text represents the combination of the text content of all nodes.

Xml. The xml content of the node is given, for example: "<FirstName> Rod </FirstName> ".

The ChildNodes set contains the child nodes of the node. To add a subnode to a node, you must first create a method for the node using the DOMDocument object, and then add the newly created node to the childNodes set of the parent node. The following code creates a subnode subroutine and adds it to the parent node using the appendChild method of the parent node:

''Add a new node to the indicated parent node.
Private sub createnode (byval indent as integer ,_
Byval parent as ixmldomnode, byval node_name as string ,_
Byval node_value as string)
Dim new_node as ixmldomnode

''Create the new node.
Set new_node = parent. ownerdocument. createelement (node_name)

''Set the node'' s text value.
New_node.text = node_value

''Add the node to the parent.
Parent. appendchild new_node
End sub

SaveValues Program

Now we can use XML to create a simple program (1), whose values are stored in the XML file. When the program starts running, the program starts from VALUE. load data in the XML file, and store the current VALUE in the program into the VALUE at the end of the program running. XML file.

 

The following code shows the structure of the VALUE. XML file:

<Values>
<Firstname> rod </firstname>
<Lastname> Stephen </lastname>
<Street> 1234 programmer place </street>
<City> bugville </city>
<State> Co </State>
<Zip> 80276 </zip>
</Values>

List1 shows how to write SaveValues. When loading a form, the form_load event triggers the LoadValues subroutine.

LoadValues creates a DOMDocument object named xml_document, loads the xml file, uses the selectSingleNode method to find the node named values, and uses the GetNodeValue method to obtain the value obtained from the descendant of the value node.

GetNodeValue uses the selectSingleNode method of the value node to find the target node. If the node does not exist, a default value is returned. If the node GetNodeValue is found, the text value of the node is returned. For data nodes in the value. xml file, text is only the text content contained in the node.

When the form is uninstalled, The form_unload event is triggered. The unload event calls the SaveValues subroutine. The program creates a new DOMDocument object, which creates a new node named value, and then adds the node to the document using the appendChild method of the document.

After creating all the new nodes, SaveValues calls the DOMDocument's save method to store the New xml file.

Note that the new file overwrites the old file. You cannot partially change the XML file by using the domdocument object. You can load the XML file, modify some of the files, and save the file, however, the original file will be completely overwritten. This is a small defect, but other programs can be used for modification at this time.

The last part of list1 is the createnode subprogram. createnode creates a new node for the parent node and assigns a value to the node. In this subroutine, A domdocument object is referenced first, and a new node is created using the createelement method of the object.

The createnode method sets the text attribute of the node, and then adds the node as a child node to the parent node.

List1:

Option explicit

Private m_apppath as string

Private sub form_load ()
''Get the application ''s startup path.
M_apppath = app. Path
If right $ (m_apppath, 1) <> "/" then m_apppath = m_apppath &"/"

''Load the values.
Loadvalues
End sub

Private sub form_unload (cancel as integer)
''Save the current values.
Savevalues
End sub

''Load saved values from XML.
Private sub loadvalues ()
Dim xml_document as domdocument
Dim values_node as ixmldomnode

''Load the document.
Set xml_document = New DOMDocument
Xml_document.Load m_AppPath & "Values. xml"

''If the file doesn' t exist, then
''Xml_document.documentelement is Nothing.
If xml_document.documentElement Is Nothing Then
''The file doesn' t exist. Do nothing.
Exit Sub
End If

''Find the Values section.
Set values_node = xml_document.selectSingleNode ("Values ")

''Read the saved values.
TxtFirstName. Text = GetNodeValue (values_node, "FirstName ","??? ")
TxtLastName. Text = GetNodeValue (values_node, "LastName ","??? ")
TxtStreet. Text = GetNodeValue (values_node, "Street ","??? ")
TxtCity. Text = GetNodeValue (values_node, "City ","??? ")
TxtState. Text = GetNodeValue (values_node, "State ","??? ")
Txtzip. Text = getnodevalue (values_node, "Zip ","??? ")
End sub

''Return the node's value.
Private function getnodevalue (byval start_at_node as ixmldomnode ,_
Byval node_name as string ,_
Optional byval default_value as string = "") as string
Dim value_node as ixmldomnode

Set value_node = start_at_node.selectsinglenode (". //" & node_name)
If value_node is nothing then
Getnodevalue = default_value
Else
Getnodevalue = value_node.text
End if
End Function

''Save the current values.
Private sub savevalues ()
Dim xml_document as domdocument
Dim values_node as ixmldomnode

''Create the XML document.
Set xml_document = new domdocument

''Create the values section node.
Set values_node = xml_document.createelement ("values ")

''Add the values section node to the document.
Xml_document.appendchild values_node

''Create nodes for the values inside
''Values section node.
Createnode values_node, "firstname", txtfirstname. Text
Createnode values_node, "lastname", txtlastname. Text
Createnode values_node, "street", txtstreet. Text
Createnode values_node, "city", txtcity. Text
Createnode values_node, "State", txtstate. Text
Createnode values_node, "Zip", txtzip. Text

''Save the XML document.
Xml_document.save m_apppath & "values. xml"
End sub

''Add a new node to the indicated parent node.
Private sub createnode (byval parent as ixmldomnode ,_
Byval node_name as string, byval node_value as string)
Dim new_node as ixmldomnode

''Create the new node.
Set new_node = parent. ownerdocument. createelement (node_name)

''Set the node'' s text value.
New_node.text = node_value

''Add the node to the parent.
Parent. appendchild new_node
End sub

Savevaluesindented Program

Although everyone has made it easier to process XML documents, XML tools generally ignore the gaps and indentation that make the XML document structure obvious, the XML Parser also ignores indentation and white space.

Unfortunately, the indentation and white space are also ignored in our example. savevalues creates an XML file like the following, and all the code is in the same line.

<Values> <firstname> rod </firstname> <lastname> Stephen </lastna
Me> <Street> 1234 programmer place </street> <city> bugville </Ci
Ty> <State> Co </State> <zip> 80276 </zip> </values>

VB. NET includes the text writing class, which can be specified by the XML document. However, MSXML does not support this function. If you need to save an XML file in a clear format, you must add another format.

List2 lists the code used by the savevaluesindented program. The savevalues subprogram is almost identical to the one mentioned in the preceding example, however, after the value node is created, a new line marked with <value> is created for the XML document.

Savevalues then calls createnode to create a new data node, but here it passes a new parameter to createnode, which indicates the indent mode of the new node.

Createnode

''Save the current values.
Private sub savevalues ()
Dim xml_document as domdocument
Dim values_node as ixmldomnode

''Create the XML document.
Set xml_document = new domdocument

''Create the values section node.
Set values_node = xml_document.createelement ("values ")

''Add a new line.
Values_node.appendchild xml_document.createtextnode (vbcrlf)

''Add the values section node to the document.
Xml_document.appendchild values_node

''Create nodes for the values inside
''Values section node.
CreateNode 4, values_node, "FirstName", txtFirstName. Text
CreateNode 4, values_node, "LastName", txtLastName. Text
CreateNode 4, values_node, "Street", txtStreet. Text
CreateNode 4, values_node, "City", txtCity. Text
CreateNode 4, values_node, "State", txtState. Text
CreateNode 4, values_node, "Zip", txtZip. Text

''Save the XML document.
Xml_document.save m_AppPath & "Values. xml"
End Sub

''Add a new node to the indicated parent node.
Private Sub CreateNode (ByVal indent As Integer ,_
ByVal parent As IXMLDOMNode, ByVal node_name As String ,_
ByVal node_value As String)
Dim new_node As IXMLDOMNode

''Indent.
Parent. appendchild parent. ownerdocument. createtextnode (space $ (indent ))

''Create the new node.
Set new_node = parent. ownerdocument. createelement (node_name)

''Set the node'' s text value.
New_node.text = node_value

''Add the node to the parent.
Parent. appendchild new_node

''Add a new line.
Parent. appendchild parent. ownerdocument. createtextnode (vbcrlf)
End sub

Conclusion

This article only reveals the surface of XML programming. The example in this article involves only a very simple XML file, but you can use the technology revealed in this article to do more things, such as configuration settings, form positions, and other information. XML has evolved further, with more complex data layers. For more complex data structures, it is easier to use MSXML objects to access XML files during runtime.

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.