后面是一个读写XML的类:
Public Class XML
Private _FileName As String
Public Property FileName() As String
Get
Return _FileName
End Get
Set(ByVal Value As String)
_FileName = Value
End Set
End Property
Public Sub New(ByVal FileName As String)
_FileName = FileName
End Sub
Public shared Function ExistFile(byval filename as string) As Boolean
Return System.IO.File.Exists(filename)
End Function
'从XML中读取数据集
Public Function Read() As DataSet
If Not ExistFile() Then
Throw New Exception("XML文件:" & _FileName & " 不存在!")
Return Nothing
End If
Dim tmpXMLRead As System.IO.FileStream
Dim tmpXMLReader As System.Xml.XmlTextReader
Try
tmpXMLRead = New System.IO.FileStream(_FileName, System.IO.FileMode.Open, IO.FileAccess.Read)
tmpXMLReader = New System.Xml.XmlTextReader(tmpXMLRead)
Dim tmpDataset As New DataSet("XML File")
tmpDataset.ReadXml(tmpXMLReader)
tmpXMLReader.Close()
tmpXMLRead.Close()
Return tmpDataset
Catch ex As Exception
If Not tmpXMLReader Is Nothing Then tmpXMLReader.Close()
If Not tmpXMLRead Is Nothing Then tmpXMLRead.Close()
Throw ex
End Try
End Function
'写数据集到XML中
Public Sub Write(ByVal XMLDataSet As DataSet)
If XMLDataSet Is Nothing Then Throw New Exception("源数据流不存在!")
Dim tmpXMLWrite As System.IO.FileStream
Dim tmpXMLWriter As System.Xml.XmlTextWriter
Try
tmpXMLWrite = New System.IO.FileStream(_FileName, System.IO.FileMode.Create)
tmpXMLWriter = New System.Xml.XmlTextWriter(tmpXMLWrite, System.Text.UTF8Encoding.UTF8)
tmpXMLWriter.Namespaces = True
tmpXMLWriter.Formatting = System.Xml.Formatting.Indented
tmpXMLWriter.IndentChar = vbTab
tmpXMLWriter.WriteStartDocument() '书写版本为“1.0”的 XML 声明。
XMLDataSet.WriteXml(tmpXMLWriter, XmlWriteMode.WriteSchema)
tmpXMLWriter.Close()
tmpXMLWrite.Close()
Catch ex As Exception
If Not tmpXMLWrite Is Nothing Then tmpXMLWrite.Close()
If Not tmpXMLWriter Is Nothing Then tmpXMLWriter.Close()
Throw ex
End Try
End Sub
End Class