這篇主要是回復網友問題時做的測試程式,原文在這邊,下面來看看測試的程式碼
XML內容是像下面這樣
Note:.net compact framework 2.0,Windows mibile 5.0
這篇主要是回復網友問題時做的測試程式,原文在這邊,下面來看看測試的程式碼
XML內容是像下面這樣
程式碼的部分
<?xmlversion="1.0"encoding="utf-8" ?>
<Application>
<DefaultSetup>
<entrykey="12"value="0000"/>
<entrykey="34"value="1111"/>
<entrykey="56"value="2222"/>
<entrykey="78"value="3333"/>
</DefaultSetup>
</Application>
Imports System.Xml
Public Class Form1
Dim xmlDoc As XmlDocument
Dim strTmp As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
xmlDoc = New Xml.XmlDocument()
''載入XML文件
xmlDoc.Load(GetAppPath() & "\test.xml")
End Sub
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim xnodelist As Xml.XmlNodeList = xmlDoc.SelectNodes(txtXPath.Text)
If xnodelist.Count > 0 Then
DisplayXmlNode(xnodelist)
Else
TextBox1.Text = "Not found"
End If
End Sub
Private Sub DisplayXmlNode(ByRef xNodeList As XmlNodeList)
For Each x As Xml.XmlNode In xNodeList
If x.HasChildNodes Then
DisplayXmlNode(x.ChildNodes)
Else
strTmp = "Node Name=" & x.Name
If x.Attributes.Count > 0 Then
For Each z As Xml.XmlAttribute In x.Attributes
strTmp &= " Attribute Name=" & z.Name & " Value=" & z.Value
If UCase(z.Name) = "KEY" Then
cboItem.Items.Add(z.Value)
End If
Next
End If
TextBox1.Text &= vbCrLf & strTmp
End If
Next
End Sub
Private Sub btnModify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnModify.Click
Dim xnodelist As Xml.XmlNodeList = xmlDoc.SelectNodes(txtXPath.Text)
If xnodelist.Count > 0 Then
ModifyValue(xnodelist)
Else
MessageBox.Show("Not found")
End If
End Sub
'''
''' 土法煉鋼修改
'''
'''
'''
Private Sub ModifyValue(ByRef xNodeList As XmlNodeList)
For Each x As Xml.XmlNode In xNodeList
If x.HasChildNodes Then
ModifyValue(x.ChildNodes)
Else
''判斷xmlNode是否有Attributes
If x.Attributes.Count > 0 Then
''尋找所有的Attributes
For Each z As Xml.XmlAttribute In x.Attributes
''判斷名稱為key且值為value的Attributes
If (UCase(z.Name) = "KEY") AndAlso (z.Value = cboItem.Text) Then
''判斷是否有value的Attributes
If x.Attributes("value") IsNot Nothing Then
''變更
x.Attributes("value").Value = txtNewValue.Text
End If
End If
Next
End If
TextBox1.Text &= vbCrLf & strTmp
End If
Next
If chkAutoSave.Checked Then xmlDoc.Save(GetAppPath() & "\test.xml")
MessageBox.Show("Modify success")
End Sub
Public Function GetAppPath() As String
Return System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly.GetName.CodeBase.ToString)
End Function
End Class
完整的程式碼可以在這邊下載