将Xml文件加载到XDocument中以便稍后在Button中使用

时间:2013-02-13 22:01:28

标签: xml vb.net visual-studio-2010 xml-parsing

我目前使用以下代码将大型Xml文件加载到XTable中:

Private Sub Button5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
  TextBox4.Visible = False
  Dim asm = Assembly.GetExecutingAssembly()
  Dim var = asm.GetManifestResourceStream("WindowsApplication2.british-english-dictionary.xml")

  Dim rand = New Random()
  Dim myXml = XDocument.Load(var)
  var.Close()

  Dim lexemeList = myXml.Descendants("lexeme").ToList()
  Dim randomLexeme = lexemeList(rand.Next(0, lexemeList.Count - 1))

  TextBox2.Text = randomLexeme.Descendants("grapheme").Value
End Sub

但是,由于xml很长(400,000个条目),按下按钮会有一点延迟。要尝试最小化它,我想按下按钮外的Dim myXml = XDocument.Load(var),以便只在打开程序时才能将Xml文件加载到XDocument,而不是每次按下按钮。< / p>

我试过这样做:

Imports System.IO
Imports System
Imports System.Reflection
Imports System.Xml
Imports System.Security.Permissions

Public Class Form1    
  Public asm = Assembly.GetExecutingAssembly()
  Public var = asm.GetManifestResourceStream("WindowsApplication2.british-english-dictionary.xml")

  Public rand = New Random()
  Public myXml = XDocument.Load(var)

  Private Sub Button5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
    TextBox4.Visible = False

    Dim lexemeList = myXml.Descendants("lexeme").ToList()
    Dim randomLexeme = lexemeList(rand.Next(0, lexemeList.Count - 1))

    TextBox2.Text = randomLexeme.Descendants("grapheme").Value
  End Sub
End Class

但是当按钮点击事件发生时我收到错误:

  

找不到类型'd__a'上的公共成员'ToList'。

1 个答案:

答案 0 :(得分:4)

你不应该在变量初始化器中做任何繁重的工作。相反,请使用Sub NewForm_Load。始终明确指定类型并为变量赋予有意义的名称。避免不必要的变量暴露,例如asm可以在Sub New内保密。例如:

Public var As Stream
Public rand As Random
Public myXml As XDocument

Sub New()
  ' This call is required by the designer.
  InitializeComponent()

  ' Add any initialization after the InitializeComponent() call.
  Dim asm As Assembly = Assembly.GetExecutingAssembly()
  var = asm.GetManifestResourceStream("WindowsApplication2.british-english-dictionary.xml")
  rand = New Random()
  myXml = XDocument.Load(var)
End Sub

从此开始,看看错误是否仍然存在。

作为旁注,如果向项目中添加资源文件(* .resx),则可以使代码更简单,然后将XML资源添加到项目中。然后它变得像调用一样简单:

myXml = XDocument.Load(My.Resources.ResxName.british-english-dictionary.xml)

注意在编译时检查资源名称,VS为你做管道。