利用Visual Basic操作XML数据
>1234 Programmer Place</Street>
<City>Bugsville</City>
<State>CO</State>
<Zip>80276</Zip>
</Values>
List1显示了怎样编写SaveValues,当载入表单时,form_load事件触发LoadValues子程序。
LoadValues创建了一个名为xml_document的DOMDocument对象,然后载入xml文件,使用selectSingleNode方法查找名为values的节点,然后使用GetNodeValue方法获得从value节点后代中得到的值。
GetNodeValue使用value节点的selectSingleNode方法寻找目标节点,如果节点不存在函数将返回一个缺省值,如果找到这个节点GetNodeValue将返回该节点的text值。对于value.xml文件中的数据节点,text仅仅是包含在节点中的文本内容。
当窗体卸载时触发form_unload事件,unload事件调用SaveValues子程序。程序创建一个新的DOMDocument对象,该对象创建一个新的名为value的节点,然后用文档的appendChild方法将节点添加到文档中。
在创建所有新的节点后,SaveValues调用DOMDocument´s save方法存储新的xml文件。
注意这个新的文件已经覆盖了旧文件,使用DOMDocument对象无法部分改变XML文件,可以加载XML文件,然后修改其中一部分,然后保存文件,但原文件将被完全覆盖。这是一个小的缺陷,但在这时可以使用其它程序进行修改。
List1的最后一部分是CreateNode子程序,CreateNode 为父节点创建一个新节点并同时给这个节点赋值。在这个子程序中首先引用一个DOMDocument对象,然后使用该对象的createElement方法创建一个新的节点。
createNode方法设置节点的text属性,然后将节点作为子节点添加到父节点中。
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
上一页 [1] [2] [3] [4] [5] 下一页
进入问吧