【问题标题】:Reading Specific Data In XML Files in Visual Basic在 Visual Basic 中读取 XML 文件中的特定数据
【发布时间】:2016-01-31 22:08:28
【问题描述】:

标题说明了一切,我想知道如何在 Visual Basic 中从 .xml 文件中读取各种数据。我当前的基本 xml 文件如下所示:

 <?xml version="1.0"?>

-<ArrayOfActivity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">


 -<activity>

 <memno>1239</memno>

 <curweek>0</curweek>

 <rundist>0</rundist>

 <runtime>0</runtime>

 <swimdist>0</swimdist>

 <swimtime>0</swimtime>

 <cycdist>0</cycdist>

 <cyctime>0</cyctime>

 </activity>


 -<activity>

 <memno>1293</memno>

 <curweek>0</curweek>

 <rundist>0</rundist>

 <runtime>0</runtime>

 <swimdist>0</swimdist>

 <swimtime>0</swimtime>

 <cycdist>0</cycdist>

 <cyctime>0</cyctime>
 </activity>
 </ArrayOfActivity>

我只想读取成员编号 1239 的值,我该怎么做?我无法理解任何在线帮助,我对 Visual Basic 还很陌生。我也是通过这个方法保存的:

 Public Sub SaveDataAct()
    If System.IO.File.Exists("e:\Test\test2.xml") = True Then
        System.IO.File.Delete("e:\Test\test2.xml")
    End If
    Dim serializer As New Xml.Serialization.XmlSerializer(GetType(List(Of activity)))
    Dim fs As New IO.FileStream("e:\Test\test2.xml", IO.FileMode.Create)
    serializer.Serialize(fs, dataentry)
    fs.Close()
End Sub

【问题讨论】:

  • 使用带有两个箭头的图标而不是图片将xml作为文本发布。
  • 这是 vb.net 不是 vba
  • 感谢格式化帮助
  • 我建议使用 Linq to Xml 而不是 XmlSerializer - 它更轻量级并且允许导航 Xml。这个thread 包含一些可以帮助您入门的简单示例。

标签: xml vb.net file parsing


【解决方案1】:

就像 Pawel 已经提到的,您应该使用 Linq to Xml。

您的示例程序如下所示:

Imports System.Linq
...

Sub Main()
    Dim input As XElement = XElement.Load("e:\Test\test2.xml") 

    //Query your Xml with Linq, almost similiar to Sql. 
    //You can extend with any where/join/group/order by clause
    Dim output = From activies In input...<activity>
                 Where Integer.Parse(activies.<memno>.Value) <= 1293
                 Select activies

    //Output is an IEnumarable of XElement
    For Each activity In output
        Console.WriteLine("Member: {0}", activity.<memno>.Value)
        Console.WriteLine("Current Week: {0}", activity.<curweek>.Value)
        //...
    Next

End Sub

如您所见,您可以使用.&lt;ChildElementName&gt;...&lt;DescendantElementName&gt; 直接通过XElement 导航,这是一个非常好的VB .NET 功能。

更多关于LINQ

【讨论】:

    【解决方案2】:

    我会将它读入这样的数据集:

     Dim XML_Read as DataSet = new DataSet
     XML_Read.ReadXML("e:\Test\test2.xml")
    

    然后你就可以通过这种方式访问​​你想要的元素了:

     XML_Read.tables("activity").Rows(0).Item("memno")
    

    【讨论】:

      猜你喜欢
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2017-10-20
      • 2014-03-17
      相关资源
      最近更新 更多