ryan2405
ryan2405

Reputation: 63

Reading Specific Data In XML Files in Visual Basic

The title says it all, I want to know how to read various pieces of data from .xml files in visual basic. My current, basic, xml file looks like:

 <?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>

I want to just read to values from, say, member number 1239, how do I go about this? I cannot make sense of any on-line help, I am fairly new to visual basic. I also save through this method:

 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

Upvotes: 0

Views: 1223

Answers (2)

Ehsan
Ehsan

Reputation: 785

I would read it to a dataset like this:

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

Then you will get access to the element you want this way:

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

Upvotes: 1

Alex B.
Alex B.

Reputation: 2167

Like already mentioned by Pawel you should rather use Linq to Xml.

Your sample program would look like:

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

As you can see you can navigate directly thru an XElement with .<ChildElementName> and with ...<DescendantElementName> which is a pretty nice VB .NET feature.

More about LINQ

Upvotes: 1

Related Questions