【问题标题】:Parsing XML file to custom class - InvalidCastException将 XML 文件解析为自定义类 - InvalidCastException
【发布时间】: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: &lt;ArrayOfItemInfo xmlns=''&gt; was not expected. 根节点是 &lt;ArrayOfItemInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; 我仍然面临同样的问题......

标签: .net xml vb.net exception-handling


【解决方案1】:

你使用了错误的类型来初始化XmlSerializer。

您的 XML 包含一个项目数组,并且您尝试将其反序列化为 List(Of ItemInfo),因此您应该使用:

Dim serializer As New XmlSerializer(lst.GetType())

而不是

Dim serializer As New XmlSerializer(GetType(ItemInfo))

反序列化为List(Of ItemInfo),而不是单个ItemInfo。

【讨论】:

  • 太棒了......这就像一个魅力......我想当我们看代码太近时,我们会错过重要的细节 :) 非常感谢@sloth :)
猜你喜欢
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
相关资源
最近更新 更多