为什么这个程序在VB 2010中不起作用

时间:2013-10-28 20:51:46

标签: xml arrays vb.net

好的,所以我在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>

我想将Name,Email和Tel放入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

1 个答案:

答案 0 :(得分:0)

这本书可能指明的不止于此,但从我们之前学到的内容来看,似乎确实涉及了一个人类:

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