【发布时间】:2014-06-02 09:36:17
【问题描述】:
我有一个自定义 XML 文件,看起来像这样,其中包含一些 'n' 条目。我正在尝试将所有值加载到 lst 变量并对其执行 foreach 循环以进行进一步处理...
<ItemInfo>
<StartTime>2014-06-16T00:00:00</StartTime>
<EndTime>2014-06-16T23:59:59</EndTime>
<Text>Calendar Project Started</Text>
<A>255</A>
<R>255</R>
<G>0</G>
<B>0</B>
</ItemInfo>
<ItemInfo>
<StartTime>2014-08-02T00:00:00</StartTime>
<EndTime>2014-08-02T23:59:59</EndTime>
<Text>First Release</Text>
<A>255</A>
<R>255</R>
<G>0</G>
<B>0</B>
</ItemInfo>
我正在尝试使用Deserialze() 方法解析它们。
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fi As System.IO.FileInfo = New IO.FileInfo(System.IO.Path.Combine(Application.StartupPath, "items.xml"))
If fi.Exists Then
Dim lst As New List(Of ItemInfo)
Dim serializer As New XmlSerializer(GetType(ItemInfo))
Dim fs As New IO.FileStream("items.xml", IO.FileMode.Open)
Dim reader As System.Xml.XmlReader = System.Xml.XmlReader.Create(fs)
lst = CTypeDynamic(serializer.Deserialize(reader), lst.GetType) '->Invalid cast Exception
fs.Close()
End If
End Sub
自定义类如下:
Public Class ItemInfo
Public StartTime As DateTime
Public EndTime As DateTime
Public Text As String
Public A As Int32
Public R As Int32
Public G As Int32
Public B As Int32
Dim pattern As HatchStyle
Dim patternColor As Color
Public Sub ItemInfo(startTime As DateTime, endTime As DateTime, text As String, color As Color)
startTime = startTime
endTime = endTime
text = text
A = color.A
R = color.R
G = color.G
B = color.B
End Sub
End Class
异常信息是:
从类型“ItemInfo”到类型“List(Of ItemInfo)”的转换无效。
关于我在哪里做错的任何指针?
【问题讨论】:
-
您的 XML 无效(缺少根节点)。
-
我从 XML 文件中删除了第一行,因为我有一个例外,因为
Additional information: <ArrayOfItemInfo xmlns=''> was not expected.根节点是<ArrayOfItemInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">我仍然面临同样的问题......
标签: .net xml vb.net exception-handling