Friday, December 13, 2024

Get and parse XML from Web Service (VB.net)

 Module Module1


    Sub Main()
        'Console.WriteLine("Hello world!")
        On Error Resume Next

        Dim StartTime, CurrTime As DateTime
        Dim XmlStr As String

        Dim XmlHttp As Object
        XmlHttp = CreateObject("Microsoft.XMLHTTP")
        XmlHttp.open("GET", "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml", False)
        XmlHttp.send()

        StartTime = Now
        While XmlHttp.ReadyState <> 4
            CurrTime = Now()
            If DateDiff("s", StartTime, CurrTime) > 60 Then XmlStr = "Error" : GoTo ExitSub
        End While

        If XmlHttp.Status <> 200 Then
            XmlStr = "Error" : GoTo ExitSub
        End If

        XmlStr = System.Text.Encoding.Default.GetString(XmlHttp.responseBody)
        Dim xmlElem = XElement.Parse(XmlStr)

        Dim ElemList As New ArrayList
        AccessElement(xmlElem, ElemList)

        For Each e In ElemList
            Console.WriteLine(e)
        Next

ExitSub:
        Console.WriteLine(XmlStr)
        Console.Read()
    End Sub

    Sub AccessElement(Element As XElement, ElemList As ArrayList)
        If Not Element.HasElements Then
            If Not ElemList.Contains(Element.Name.LocalName) Then ElemList.Add(Element.Name.LocalName)

            For Each Attr In Element.Attributes
                If Not ElemList.Contains(Attr.Name.LocalName) Then ElemList.Add(Attr.Name.LocalName)
            Next

        Else
            For Each Elem In Element.Elements
                AccessElement(Elem, ElemList)
            Next
        End If
    End Sub

End Module

No comments:

Post a Comment