SeaSide SeaSide - 3 months ago 14
Vb.net Question

How to get attribut value from xml element?

I have the following xml which I take from specified url:

<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>...</gesmes:subject>
<gesmes:Sender>...</gesmes:Sender>
<Cube>
<Cube time="2016-08-16">
<Cube value="1" />
<Cube value="2"/>
<Cube value="3"/>
</Cube>
</Cube>
</gesmes:Envelope>


From this file I only need to take time value '2016-08-16' using Visual Basic code.

Answer

Try xml linq

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)
        Dim _date As DateTime = CType(doc.Descendants().Where(Function(x) (x.Name.LocalName = "Cube") And (Not x.Attribute("time") Is Nothing)).Select(Function(x) x.Attribute("time")).FirstOrDefault(), DateTime)
    End Sub

End Module
Comments