在Visual Basic中读取XML文件中的特定数据

时间:2016-01-31 22:08:29

标签: xml vb.net file parsing

标题说明了一切,我想知道如何从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

2 个答案:

答案 0 :(得分:1)

就像Pawel已经提到的那样,你应该使用Linq来实现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

正如您所看到的,您可以通过带有.<ChildElementName>...<DescendantElementName>的XElement直接导航,这是一个非常好的VB .NET功能。

有关LINQ

的更多信息

答案 1 :(得分:0)

我会将其读取到这样的数据集中:

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

然后,您将通过这种方式访问​​所需的元素:

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