这并不完全是您要问的,但我发现处理原始 XML 会导致很多头痛。相反,您可能会考虑处理一个 Shift 类,该类允许您在登录/注销时执行逻辑,并让 .NET 为您执行序列化/反序列化。
这样,如果您的业务对象和关系发生变化,您就不会被绑定到特定的 XML 路径。
再说一次,不是你问的,而是我将如何解决你正在处理的业务案例。
首先,创建一个可以放入业务逻辑的班次类。这里的简单示例:
Public Class Shift
Public Property Name As String
Public Property DateString As String
Public Property Login As String
Public Property Logout As String
End Class
接下来,创建一个班次集合。我称这个类为 TimeCollection,但你可以随意调用它。将其标记为 Serializable,以便 .NET 可以完成将其从对象转换为 XML 的工作,反之亦然。
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Imports System.Xml.Serialization
<Serializable()> Public Class TimeCollection
Public Property Path As String
<XmlArray("Shifts")>
<XmlArrayItem(GetType(Shift))>
Public Property Shift As Shift()
Public Function Serialize(FileInfo As System.IO.FileInfo)
Try
If File.Exists(FileInfo.FullName) Then
File.Delete(FileInfo.FullName)
End If
If Not Directory.Exists(FileInfo.DirectoryName) Then
Directory.CreateDirectory(FileInfo.DirectoryName)
End If
Me.Path = FileInfo.FullName
Dim serializer As XmlSerializer = New XmlSerializer(GetType(TimeCollection))
Dim writer As StreamWriter = New StreamWriter(FileInfo.FullName)
serializer.Serialize(writer, Me)
writer.Close()
Catch ex As Exception
Throw
End Try
End Function
Public Shared Function Deserialize(FileInfo As FileInfo) As TimeCollection
Dim serializedType As TimeCollection = Nothing
Dim path As String = FileInfo.FullName
If (Not File.Exists(path)) Then
Deserialize = serializedType
Else
Try
Dim serializer As XmlSerializer = New XmlSerializer(GetType(TimeCollection))
Dim reader As StreamReader = New StreamReader(path)
serializedType = serializer.Deserialize(reader)
reader.Close()
Deserialize = serializedType
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If
End Function
End Class
现在。如果您有一些代码会生成一系列班次,如下所示:
Dim tc As TimeCollection = New TimeCollection()
Dim first As Shift = New Shift()
first.Name = "Philipp"
first.Login = "14:11"
first.Logout = "14:45"
first.DateString = "3/31/2013"
Dim second As Shift = New Shift()
second.Name = "Phillip"
second.Login = "14:09"
' second.Logout = "15:01" (note 2nd shift has no logout)
second.DateString = "4/1/2013"
tc.Shift = New Shift(1) {first, second}
您可以像这样轻松地序列化 TimeCollection 对象:
tc.Serialize(New FileInfo("C:\SomePath\TimeCollectionA.xml"))
它创建了以下内容:
<?xml version="1.0" encoding="utf-8"?>
<TimeCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Path>C:\Temp\Tc.xml</Path>
<Shifts>
<Shift>
<Name>Philipp</Name>
<DateString>3/31/2013</DateString>
<Login>14:11</Login>
<Logout>14:45</Logout>
</Shift>
<Shift>
<Name>Phillip</Name>
<DateString>4/1/2013</DateString>
<Login>14:09</Login>
</Shift>
</Shifts>
</TimeCollection>
然后,要反序列化内容并将文件转换回对象集合,您可以执行以下操作:
Dim tc As TimeCollection
tc = TimeCollection.Deserialize(New FileInfo("C:\SomePath\TimeCollectionA.xml"))
现在您可以遍历 tc.Shift 数组等。