0

好的,所以我在 vb 2010 中得到了很多帮助。如果你愿意的话,我需要你们提供更多的帮助。

我这里有一个 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<!--XML Database.-->
<Data>
  <Person>
    <Name>hi</Name>
    <Email>222</Email>
    <Tel>2345</Tel>
  </Person>
  <Person>
    <Name>hank</Name>
    <Email>222</Email>
    <Tel>2345</Tel>
  </Person>
</Data>

我想将姓名、电子邮件和电话放入 3 个单独的数组中。我想我明白了。但是为什么现在不工作了。这里有什么问题。

Imports System.Xml
Imports System.IO

Public Class Form2
    Dim array() As String
    Dim testname As String
    Dim namearray(1) As String
    Dim emailarray(1) As String
    Dim telarray(1) As String

    Public Const path As String = "MyName.xml" 'it is in the bin folder.

    Public Sub GetPerson()

        Dim x As Integer = 0
        Dim settings As New XmlReaderSettings
        settings.IgnoreComments = True
        settings.IgnoreWhitespace = True

        Dim xmlIn As XmlReader = XmlReader.Create(path, settings)

        If xmlIn.ReadToDescendant("Person") Then
            Do
                Dim person As New Person
                xmlIn.ReadStartElement("Person")
                namearray(x) = xmlIn("Name")
                emailarray(x) = xmlIn("Email")
                telarray(x) = xmlIn("Tel")
                x = x + 1
            Loop While xmlIn.ReadToNextSibling("Person")
        End If


        xmlIn.Close()


    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        GetPerson()
        Search.Text = namearray(0)

    End Sub

    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load



    End Sub
End Class
4

1 回答 1

0

这本书可能指定的不止这些,但根据我们之前了解到的,似乎确实涉及到一个 Person 类:

Friend Class Person
    Friend Name as String = ""
    Friend EMail As String =""
    Friend Phone as String = ""
End Class

Friend People As List(of Person)

读取 XML;在循环:

  ' I dont like instance names the same as Type names:
  Dim p As New Person
  xmlIn.ReadStartElement("Person")
  P.Name=xmlIn("Name")
  P.EMail = xmlIn("Email")
  P.Phone = xmlIn("Tel")

  ' Person now holds all the data for a this person.
  ' add him/her to the list:
  People.Add(p)

  ...
  n = 1
  For n as integer = 0 to People.Count-1
      console.WriteLine("Person #{0} is named {1)",n, People(n).Name)
  next n

不要让半混淆结构(Of..)混淆你。该Of子句所做的只是指定将要进入此列表的内容。.NET 中还有许多其他有用的集合类型,例如 Dictionary 和 ArrayList,具体取决于手头的工作。

List 的价值在于您不必知道要加载多少东西。此外,类允许数据保持在一起,而不是将与单个事物(人)相关的数据存储在不同的数组中。想象一下,如果您必须收集职业、雇主、地址、城市、州/省、婚姻状况、性别等等等,您将拥有多少个数组以及将所有内容放在一起会有多困难。

于 2013-10-28T21:10:29.383 回答