我尝试使用“using”和“.close()”但是当我想覆盖文件时仍然会出错。
正如您所看到的那样,读取和写入xml文件是在同一个应用程序中,但形式不同,这就是为什么每次我在首次读取文件后覆盖文件时都会收到错误
以下代码适用于创建xml文件的form1:
Imports System.Xml
Imports System.IO
Imports System
Public Class Form1
Private Sub saveXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveXML.Click
Dim settings As New XmlWriterSettings()
settings.Indent = False
' Initialize the XmlWriter.
Dim XmlWrt As XmlWriter = XmlWriter.Create(cbFileName.Text, settings)
With XmlWrt
' Write the Xml declaration.
.WriteStartDocument()
' Write a comment.
.WriteComment("XML Database.")
' Write the root element.
.WriteStartElement("Data")
' Start our first person.
.WriteStartElement("Person")
' The person nodes.
.WriteStartElement("Name")
.WriteString(txtFullName.Text.ToString())
.WriteEndElement()
.WriteStartElement("Email")
.WriteString(txtEmailAddress.Text.ToString())
.WriteEndElement()
.WriteStartElement("Tel")
.WriteString(txtPhoneNumber.Text.ToString())
.WriteEndElement()
' The end of this person.
.WriteEndElement()
' Close the XmlTextWriter.
.WriteEndDocument()
.Close()
End With
MessageBox.Show("XML file saved.")
End Sub
Private Sub btnOpenForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenForm.Click
form2.show()
End Sub
End Class
以下代码用于阅读:
Imports System.Xml
Public Class Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (ComboBox1.Text = "") Then
MessageBox.Show("No file name entered")
Else
If (System.IO.File.Exists(ComboBox1.Text.ToString())) Then
Dim document As XmlReader = New XmlTextReader(ComboBox1.Text.ToString())
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "Name") Then
xmlMyName.Visible = True
xmlMyName.Text = document.ReadInnerXml.ToString()
End If
If (document.Name = "Email") Then
xmlMyEmail.Visible = True
xmlMyEmail.Text = document.ReadInnerXml.ToString()
End If
If (document.Name = "Tel") Then
xmlMyTel.Visible = True
xmlMyTel.Text = document.ReadInnerXml.ToString()
End If
If (document.Name = "Notes") Then
xmlMyNotes.Visible = True
xmlMyNotes.Text = document.ReadInnerXml.ToString()
End If
End If
End While
Else
MessageBox.Show("The filename you selected was not found.")
End If
End If
End Sub
End Class