SeaSide
SeaSide

Reputation: 149

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.

Upvotes: 0

Views: 126

Answers (2)

jdweng
jdweng

Reputation: 34421

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

Upvotes: 1

FloatingKiwi
FloatingKiwi

Reputation: 4506

Add these imports:

Imports <xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01">
Imports <xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">

Then load your data however you wish into an XDocument or XElement

Dim xmlDoc = XDocument.Load("myxml.xml")

The query it as follows. (if you're using XElement don't include Root).

Dim time = xmlDoc.Root.<Cube>.<Cube>.@time

Upvotes: 1

Related Questions