使用从xml文件读取的随机值填充列表框

时间:2020-10-12 19:32:32

标签: xml vb.net

我有一个包含50本书的xml。它具有以下格式:

<livres>
    <livre>
        <ID>1</ID>
        <Title>Da Vinci Code,The</Title>
        <Author>Brown, Dan</Author>
        <Price>13.99</Price>
    </livre>

    <livre>
        <ID>2</ID>
        <Title>Harry Potter and the Deathly Hallows</Title>
        <Author>Rowling, J.K.</Author>
        <Price>17.98</Price>
    </livre>

    <livre>
        <ID>3</ID>
        <Title>Harry Potter and the Philosopher&apos;s Stone</Title>
        <Author>Rowling, J.K.</Author>
        <Price>19.99</Price>
    </livre>
</livres>

我正在尝试将10个随机条目添加到列表框中。这是我的代码:

Private Sub MySub_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        xml.main()

        Randomize()
        Dim index As Integer

        For i As Integer = 1 To 10
            index = Int((49 * Rnd()) + 0)
            lstLivres.Items.Add(Livres(index).Title)
        Next
    End Sub

xml.Main()引用此模块中的主要子目录:

Imports System.Xml

Module xml
    Public Livres(49) As Livre

    Public Structure Livre
        Public Property ID As Integer
        Public Property Title As String
        Public Property Author As String
        Public Property Price As Double
    End Structure

    Sub main()
        Dim xmlR = XmlReader.Create("Livres.xml")

        For i As Integer = 0 To 49
            Do While xmlR.Read
                If xmlR.NodeType = XmlNodeType.Element AndAlso xmlR.Name = "ID" Then
                    Livres(i).ID = xmlR.ReadElementContentAsInt
                ElseIf xmlR.NodeType = XmlNodeType.Element AndAlso xmlR.Name = "Title" Then
                    Livres(i).Title = xmlR.ReadElementContentAsString
                ElseIf xmlR.NodeType = XmlNodeType.Element AndAlso xmlR.Name = "Author" Then
                    Livres(i).Author = xmlR.ReadElementContentAsString
                ElseIf xmlR.NodeType = XmlNodeType.Element AndAlso xmlR.Name = "Price" Then
                    Livres(i).Price = xmlR.ReadElementContentAsDouble
                Else
                    xmlR.Read()
                End If
            Loop
        Next
    End Sub
End Module

我收到一条错误消息,因为由于某些原因,“ Livres(index).Title”对于任何“ index”值始终为“ Nothing”。

System.ArgumentNullException:'值不能为null。 参数名称:item'

这是为什么?它不应该与ID等于“索引”的书名相等吗?

0 个答案:

没有答案