Manipulating XML data with VisualBasic

Source: Internet
Author: User
Tags add end net object model string sort tag name version
visual|xml| data

What is XML

Extensible Markup Language XML is a simple data storage language that uses a series of simple tags to describe data that can be built in a convenient way, although XML takes up more space than binary data, but XML is extremely simple and easy to master and use.

Unlike databases such as access,oracle and SQL Server, the database provides more robust data storage and analysis capabilities, such as data indexing, sorting, lookup, correlation consistency, and so on, and XML is just presenting data. In fact, the biggest difference between XML and other data forms is that he is extremely simple. This is an advantage that looks trivial, but it makes XML unique.

The simplicity of XML makes it easy to read and write data in any application. This makes XML quickly the only common language for data exchange, although different applications support other data interchange formats, but they will soon support XML, which means that programs can be easier to connect with Windows, Mac OS, The combination of Linux and the information generated under other platforms can then easily load XML data into the program and analyze it and output the results in XML format.

The benefits of XML

We talked about XML longer than exchanging data between different applications, XML files are also easy to build small databases, and not long ago, software used INI file to store configuration information, user parameters and other information, then Microsoft introduced the system registry, then Microsoft told us that we should not use the INI file, Since then, Visual Basic's support for the INI file has been compromised. Unfortunately, the registry has several fatal drawbacks: it is not a simple text file, it is difficult to read and write, it can become large and slow, and if the registry somehow problems, it can cause the system to panic.

Placing configuration information in an XML file avoids these problems, and even sets the XML file to a shared file so that users on different computers can share the data, which is unmatched by the registry.

You can use XML directly in Web pages in a asp.net called next-generation ASP, and you can use data-bound controls to bind data directly and display it automatically.

Of course, you can not choose the XML, the use of text files, registry, database can complete the tasks that XML can do, XML is just another tool for data storage and recovery.

Introduction to XML syntax

XML syntax is very simple, XML documents are composed of nodes, using the open and Close node description tag, in the format and HTML tags very similar, the biggest difference between them is: XML can freely define the tag name. For example, the following tag describes a phone number:

987-654-3210

And you can use it without declaring a tag name.

The start and end tags must be the same, and the XML is case-sensitive, so the case of the tag must be the same. For example, in the above example, the tag must end with a tag, not or

A node tag can contain attributes, such as the following code in which the phone node contains the attribute type with a value of Workfax:

987-654-3210

If you do not want to include a value in the node, you can use the end tag without closing, and you can end the node with a slash in the back of the start tag, in the following example, the number property of the phone tag stores a phone call, so you don't need an end tag:

The structure of an XML document is a hierarchical structure of trees. The document must have a unique root node that contains all the other nodes. Here is a more complete example:


Andy
Fickle
1234 Programmer Place
Bugsville
CO
82379
354-493-9489

Betty
Masterson
937-878-4958
937-878-4900

...

Note Similar nodes do not need to contain the same information, such as the first entry node contains address information and home phone numbers, and the second entry node contains work and Workfax phone numbers, not the information contained in the first entry node.
XML tools

As the previous example shows, XML syntax is so simple that you can make an XML parser in a very short time, and fortunately you don't have to, because XML tools can run on a variety of platforms, including windows that can have Visual Basic installed.

It is these l tools, not the XML itself, that make XML more powerful and complex. Instead of a different parser that allows you to load an entire XML document at a time or load only one node, 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 get names or attributes, and sort the results. Although their functionality does not have a real relational database, these features of Dom are still very useful.

XSD can define the format of an XML document, and the XSL Extension style sheet defines how to convert an XML document into a file format, such as an HTML file, that can be browsed in a Web browser.

These tools are actually more complex than XML itself, so all of the books that explain XML spend a lot of time explaining these XML tools. But this is beyond the scope of this article, interested readers can refer to the relevant information.

Visual Basic.NET provides complete tools for using XML, XSL, and other XML tools. But without waiting for vb.net, Microsoft XML Core Services (MSXML) version 4.0 provides tools to load and store XML documents from Visual Basic6.0.

Download the latest version of MSXML in msdn.microsoft.com/xml/default.asp and install it on your computer. Using Microsoft XML V4.0 as references to other objects in Visual Basic 6.0, first select the Reference menu item in the Project menu, select Microsoft V4.0, click OK, and then you can add XML objects to your VB application as soon as you're done.

DOMDocument class

The Document Object Model (DOM) describes the hierarchical state of an XML document using a series of corresponding objects, the DOMDocument class is a MSXML class that depicts the DOM structure of an XML document.

The DOMDocument class provides only a few useful properties and methods. The Load method loads an XML file, and the Loadxml method adds the string as XML data to the object. For example, the following code adds a small XML file to a document named Xml_document.

Dim Xml_document as New DOMDocument

Xml_document.loadxml _
" " & VbCrLf & _
" Rod " & VbCrLf & _
" Stephens " & VbCrLf & _
""

DOMDocument's XML attributes return the XML description of the document, display the return values to see what the document looks like, or store it as a file, but this is completely unnecessary because the DOMDocument object's Save method has automatically stored them.

The DocumentElement property of the DOMDocument object represents the root node of the document data, which is typically the case where the XML document is manipulated.

DOMDocument provides several ways to create new nodes. The CreateElement method creates a new element node for the document, and other methods for creating nodes are CreateAttribute, createprocessinginstruction, and createTextNode, which are not introduced here.

IXMLDOMNode class

The IXMLDOMNode class describes a node that provides a series of properties and methods for searching and manipulating XML documents.
The selectSingleNode method is used to search for descendants of the specified node, and the language used to search for the specified node path, called Xpath,xpath, is tricky, and this article does not elaborate on its specification. Here we will look at two useful and simple methods for searching child nodes.

To enter the name of the child node in the selectSingleNode method, the method will match the exact search to the child nodes of the node. If you precede the input string with ".//", then all descendants of the node 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")

Some of the most useful properties of the IXMLDOMNode object are listed below:

Attributes. Node Properties collection

NodeName. The tag name of the node

nodetypestring. Type of Node

Ownerdocument. Returns the node contained by the DOMDocument object

Text. Represents the textual content that the node contains. If the node contains other nodes, then text represents a combination of the text content of all nodes.

XML. Gives the XML content of the node, for example: " Rod ."

The ChildNodes collection contains the child nodes of the node. To add a child node to a node, you must first create a method for the node that uses the DOMDocument object, and then add the newly created node to the ChildNodes collection of the parent node. The following code shows the subroutine that creates a new child node and joins 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 (Figure 1), whose value is stored in an XML file, when the program starts running, the program loads the data from the Value.xml file, and at the end of the program, the current value in the program is saved to the Value.xml file.

The following code shows the structure of the Value.xml file:


Rod
Stephens
1234 Programmer Place
Bugsville
CO
80276

List1 shows how to write Savevalues, and when the form is loaded, the Form_Load event triggers the Loadvalues subroutine.

Loadvalues creates a DOMDocument object named Xml_document, then loads the XML file and uses the selectSingleNode method to find the node named values. The Getnodevalue method is then used to obtain the values derived from the descendants of the value node.

Getnodevalue uses the selectSingleNode method of the value node to find the target node, if the node does not exist, the function returns a default value, and if the node Getnodevalue is found, the node's text value is returned. For the data node in the Value.xml file, text is just the textual content contained in the node.

The Form_Unload event is triggered when the form unloads, and the Unload event invokes the Savevalues subroutine. The program creates a new DOMDocument object that creates a new node named value, and then adds the node to the document using the document's AppendChild method.

After all the new nodes have been created, Savevalues calls the DOMDocument ' Save method to store the new XML file.

Note that this new file has been overwritten with the old file, the DOMDocument object cannot partially change the XML file, you can load the XML file, then modify some of it, and then save the file, but the original file will be completely overwritten. This is a minor flaw, but you can use other programs to modify it at this point.

The last part of the List1 is the CreateNode subroutine, where CreateNode creates a new node for the parent node and assigns values to the node at the same time. In this subroutine, you first reference a DOMDocument object, and then use the object's CreateElement method to create a new node.

The CreateNode method sets the Text property 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. Doing 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 the
' 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 a lot of energy to work with XML documents to make them look easier, XML tools generally ignore the whitespace and indentation that make XML documents structurally clear, and the XML parser ignores indentation and whitespace as well.

Unfortunately, our example also ignores these indents and whitespace, Savevalues creates an XML file like the one below, all of which are in the same line.

Rod Stephensme> 1234 Programmer Place Bugsvillety> CO 80276

Vb. NET includes text writing classes, which can be formatted in XML documents. However, MSXML does not have this functionality, so if you need to save the XML file in a clear format, you can only add its format separately.

LIST2 lists the code that the program savevaluesindented uses, and the Savevalues subroutine is almost exactly the same as in the example above, but he creates a new row of tags for the XML document after creating the value node.

Then Savevalues calls CreateNode to create a new data node, but here it passes to createnode a new parameter that represents the indentation 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 the
' 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, and the examples in this article involve just very simple XML files, but you can do more with the techniques that are revealed in this article, such as configuration settings, form locations, and other information. XML has gone a step further, with a more complex level of data. For more complex data structures, it is easier to use MSXML objects to access XML files at run time



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.