Home > OS >  Read Data From XML File on Visual Basic
Read Data From XML File on Visual Basic

Time:09-16

I know there are many ways to read from xml file, but my xml file doesn't have data on childnodes. for Example;

<timetable>
 <periods options="canadd,export:silent" columns="period,name,short,starttime,endtime">
   <period name="1.Lesson" short="1" period="1" starttime="09:00" endtime="09:30" />
   <period name="2.Lesson" short="2" period="2" starttime="09:40" endtime="10:10" />
   <period name="3.Lesson" short="3" period="3" starttime="10:20" endtime="10:50" />
   <period name="4.Lesson" short="4" period="4" starttime="11:00" endtime="11:30" />
   <period name="5.Lesson" short="5" period="5" starttime="11:20" endtime="12:50" />
 </periods>
</timetable>

Here name, short, period, starttime and endtime are not a childnode. I want to get the list of data writen in name, short, period, starttime and endtime.

CodePudding user response:

Do this:

Dim ds as New DataSet
ds.ReadXml("path to your xml file")

Now the data you want is in

ds.Tables("period")

enter image description here

Example:

For Each ro as DataRow in ds.Tables("period").Rows
  Console.WriteLine(ro("name"))
Next ro

CodePudding user response:

Convert XML to Class.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim xe As XElement
    Dim path As String = "path to file here"
    ' xe = XElement.Load(path)
    '
    ' for testing use literal
    xe = <timetable>
             <periods options="canadd,export:silent" columns="period,name,short,starttime,endtime">
                 <period name="1.Lesson" short="1" period="1" starttime="09:00" endtime="09:30"/>
                 <period name="2.Lesson" short="2" period="2" starttime="09:40" endtime="10:10"/>
                 <period name="3.Lesson" short="3" period="3" starttime="10:20" endtime="10:50"/>
                 <period name="4.Lesson" short="4" period="4" starttime="11:00" endtime="11:30"/>
                 <period name="5.Lesson" short="5" period="5" starttime="11:20" endtime="12:50"/>
             </periods>
         </timetable>

    Dim l As New List(Of Foo)
    For Each p As XElement In xe.<periods>.Elements
        l.Add(New Foo(p))
    Next
End Sub

Public Class Foo
    Public Property Name As String
    Public Property ShortV As String
    Public Property Period As String
    Public Property StartTime As String
    Public Property EndTime As String

    Public Sub New(el As XElement)
        Me.Name = el.@name
        Me.ShortV = el.@short
        Me.Period = el.@period
        Me.StartTime = el.@starttime
        Me.EndTime = el.@endtime
    End Sub
End Class
  • Related