Source:
http://www.it.com.cn/f/edu/0410/21/37887.htm
Using the VB Operation XML Data Yeode Network 2004-10-21 16:12:00 / Crystal What is an XML Extension Markup Language XML is a simple data storage language that uses a series of simple tag descriptive data, and these tags can be used Convenient way to establish, although the space occupied by XML is more space than binary data, XML is extremely easy to master and use. Unlike databases such as Access, Oracle, and SQL Server, the database provides stronger data storage and analysis capabilities, such as data index, sort, lookup, related consistency, etc., XML is just display data. In fact, XML and other data expressions are the most different: he is extremely simple. This is an advantage that it looks a bit trivial, but it is this point to make XML different. XML is simple to read and write data in any application, which makes XML soon become the only public language of data exchange, although different application software also supports other data exchange formats, but will soon support XML, Then, the program can be more easier to combine the information generated under Windows, Mac OS, Linux, and other platforms, and then easily load XML data into the program and analyze him, and output the results in XML format. The advantage of XML We talk about the XML longer than exchange data between different applications, and the XML file is also facilitated to build a small database. Soon, the software uses the INI file to store configuration information, user parameters, and other information, and later Microsoft introduced the system Registry, next Microsoft tells us that the INI file should not be used again, from which Visual Basic's support for the INI file is weakened. But unfortunately, the registry has several fatal disadvantages: it is not a simple text file, it is difficult to read and write, which may become huge and slow. If the registry does not know what problems, it will cause the system to crash. Place the configuration information in the XML file to avoid these issues, and even set the XML file to a shared file, so that users on different computers can share data, which is the registry cannot match. In the ASP.NET known as the next generation ASP, you can use XML directly in the web page, you can use the data binding control to bind the data directly and automatically display. Of course, you can also choose XML, you can use text files, registry, and databases can complete the task that XML can complete. XML is just another tool for data storage and recovery. XML syntax introduction XML's syntax is very simple, XML document consists of nodes, using open and off node description tags, very similar to HTML tag, and the maximum difference between them can be freely defined in the XML. For example, the following tags describe a phone number:
987-654-3210 phone> and can be used without a declaration marker name. The start and end tags must be the same, and XML is identified. So the size of the tag must also be the same. For example, in the above example, you must end with the phone> tag, without the phone> or phone> node tag, such as the PHONE node, in the following code contains the properties Type. , Its value is Workfax:
987-654-3210 If you don't want to include a value in the node, you can use the end tag, you can use a slash to end the node after starting the label. In the example, the Number property of the Phone tag stores a phone number, so there is no need to end the tag: XML document structure is a tree Level structure. The documentation must have a unique root node, and the root node contains all other nodes. Let's take a more complete example:
andy firstname> fickle lastname> 1234 programer place street> bugsville city> Co < / State> 82379 zip> 354-493-9489 phone> entry> betty firstname> Masterson lastname> 937-878-4958 phone> 937-878-4900 phone> entry> ... addresses > Note Similar nodes do not need to include the same information, such as the first Entry node contains address information and home phone numbers, and the second Entry node contains the Work and Workfax phone numbers, without including the first Entry node. information. XML tools are shown in the previous example, 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 XML tools can run on a variety of platforms, including Visual Basic's Windows installed. It is these L tools instead of XML itself make XML more powerful and complicated. Different parsers allow you to load the entire XML document at a time or only load a node. Instead, 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 get name or properties, and sort the results. Although their features have no real relationship database power, these features of DOM are still very useful. XSD can define the format of the XML document, the XSL extension style order defines how to convert an XML document into other file formats that can be viewed in a web browser, such as an HTML file. These tools are actually more complicated than XML itself, so all books that explain XML have spent a lot of space to explain these XML tools. However, this exceeds the scope of this article, and interested readers can refer to the relevant information. Visual Basic.net provides a full tool for using XML, XSL, and other XML tools. But don't wait for VB.NET, Microsoft XML Core Services (MSXML) version 4.0 provides tools that load and store XML documents from Visual Basic 6.0. Download the latest version of MSXML in msdn.microsoft.com/xml/default.asp and install it on your computer.
Like other objects in Visual Basic 6.0, you first select the reference menu item in the engineering menu, select Microsoft V4.0, click OK, and now you can add it to the VB application now. XML objects. DomDocument Class Document Object Model (DOM) uses a series of corresponding objects to describe the level of XML documents, the DomDocument class is a MSXML class that depicts the DOM structure of the XML document. The DomDocument class only provides few a few useful properties and methods. The LOAD method loads an XML file, and the LoadXML method adds a string as an XML data to the object. For example, the following code adds a small XML file to a document called XML_Document. Dim xml_document As New DOMDocumentxml_document.loadXML _ "" & vbCrLf & _ " Rod FirstName>" & vbCrLf & _ " Stephens LastName>" & vbCrLf & _ " Person> "DomDocument's XML property returns the XML description of the document, you can display these return values to see what these documents look like, but it can be stored as a file, but this is completely unnecessary, because the Save method of the DomDocument object has automatically Store it. The DOCUMENTELEMENT attribute of the DomDocument object represents the root point of the document data, usually the operation of the XML document begins here. DomDocument provides several ways to create new nodes. The CreateElement method creates a new element node for documentation, and other methods for creating nodes have CreateAttribute, CreateProcessinginstruction, and CreateTextNode, which is not described here. The IxmlDomnode class IXMLDomnode class describes a node that provides a range of properties and methods for searching and manipulating XML documents. SELECTSINGLENODE method is used to search for future generations of specified nodes, and the language used to search for specified node paths is called XPath, XPath is very difficult, this article does not specify in detail. Below we will introduce two methods for the search child nodes and simple methods. In the Selectsinglenode method, the name of the input sub-node, the method will exactly match the search in the child node of the node. If you add ".//" in front of the input string, you will search for all future generations of nodes.
'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") are listed below The part of the IXmldomnode object is very useful: attributes. Node property set nodename. Node's tag name nodetypeString. Node's type OwnerDocument. Returns the Node text containing the DomDocument object. Indicates the text content containing the node. If the node contains other nodes, Text represents a combination of text content of all nodes. XML. The XML content of the node is given, for example: " rod firstname>". ChildNodes collection contains the child's child node. To add a child node to the node, you must first create a method to use the node of the DomDocument object, and then add this new node to the ChildNodes collection of the parent node. The following code shows the subroutine that creates a new child node and adds it to the parent node using the AppendChild method of the parent node: 'Add a new node to the indeed parent node.private sub createenode (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_NodeND Sub SaveValues Now we can use XML to create a simple program (Figure 1), which stored in the XML file, in the program starts running, the program is from the value.xml file Load data, store the current value in the program in the Value.xml file at the end of the program run. The following code is the structure of the Value.xml file:
Rod firstname> Stephens lastname> 1234 programer place street> bugsville city> co state> 80276 < / Zip> value> List1 shows how to write SaveVALUES, when loading a form, the Form_Load event triggers the loadVALUES subroutine. LoadValues created a DomDocument object called XML_Document, then loaded into the XML file, using the Selectsinglenode method to find the node named VALUES, then use the GetNodeValue method to get the value obtained from the generation from the Value node. GetNodeValue uses the SelectsingLEnode method of the Value node to find the target node. If the node does not exist that the function will return a default value, if this node getnodeValue will return the TEXT value of the node. For the data nodes in the value.xml file, Text is only the text content included in the node. Trigger the form_unload event when the form is uninstalled, and the unload event calls the SaveVALUES subroutine. The program creates a new DomDocument object that creates a new node called Value and adds the node to the document with the AppendChild method of the document. After creating all new nodes, SaveValues calls the DomDocument's Save method to store the new XML file. Note that this new file has overwrites the old file. Use the DomDocument object to change the XML file, you can load the XML file, then modify some of the part, then save the file, but the original file will be completely overwritten. This is a small defect, but other programs can be modified at this time. The last part of List1 is the CreateNode subroutine, CreateNode creates a new node for the parent node and assigns this node. In this subroutine first reference a DomDocument object, then create a new node using the CreateElement method of the object. The CreateNode method sets the Text property of the node and then adds the node as the child node to the parent node. List1:
Option ExplicitPrivate m_AppPath As StringPrivate Sub Form_Load () 'Get the application's startup path.m_AppPath = App.PathIf Right $ (m_AppPath, 1) <> "" Then m_AppPath = m_AppPath & ""' Load the values.LoadValuesEnd SubPrivate Sub Form_Unload (Cancel As Integer) 'Save the current values.SaveValuesEnd Sub' Load saved values from XML.Private Sub LoadValues () Dim xml_document As DOMDocumentDim values_node As IXMLDOMNode 'Load the document.Set xml_document = New DOMDocumentxml_document.Load m_AppPath & "Values.xml"' If the file does not exist, then 'xml_document.documentElement is Nothing.If xml_document.documentElement Is Nothing Then' The file does not exist. Do nothing.Exit SubEnd 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 = GetNo DeValue (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 StringDim value_node As IXMLDOMNodeSet value_node = start_at_node.selectSingleNode ( ".//" & node_name) IF value_node is nothing thengeTnodevalue =
default_valueElseGetNodeValue = value_node.TextEnd IfEnd Function 'Save the current values.Private Sub SaveValues () Dim xml_document As DOMDocumentDim 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.TextCreateNode values_node, "LastName", txtLastName.TextCreateNode values_node, "Street", txtStreet.TextCreateNode values_node, "City", txtCity.TextCreateNode values_node, "State", txtState.TextCreateNode values_node, "Zip", txtZip.Text 'Save the XML document.xml_document.save m_AppPath & "Values. XML "End Sub 'Add A New Node To The Compicated Parent Node.private Sub Createnode (Byval Node_name As String, Byval Node_Value As String) DIM New_Node As IXMLD OMNode '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_nodeEnd Sub SaveValuesIndented program although everyone of Great energy to deal with the XML document, so that they look more easier, but XML tools generally ignore the blank and indentation of the XML document structure, and the XML parser also ignores indentation and blank. Unfortunately, our example also ignores these indentation and blank, SaveValues created an XML file like the following, all the code is in the same line.
Rod firstname> Stephens lastname> 1234 programer place street> bugsville city> co state> 80276 < / Zip> values> VB.NET includes text writing classes, which can be formatted in XML documents. But MSXML has no such function, so if you need to save an XML file in a clear format, you can only add its format. List2 lists the code used by the program SaveVALUESInTED, and the SaveVALUES subroutine is almost identical to the above example, but he created a tag for the XML document after creating the Value node. The SaveValues then invokes CreateNode to create a new data node, but here it passes a new parameter for CreateNode, which indicates the indentation of this new node. Createnode