2016-08-17 51 views
0

我有以下XML這是我從指定的網址採取:如何從xml元素獲取屬性值?

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

從這個文件我只需要使用Visual Basic代碼,以時間價值「2016年8月16日」。

回答

1

嘗試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 
1

添加這些進口:

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

但是你想成爲一個XDocument或的XElement

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

它如下查詢然後加載數據。 (如果您使用的XElement不包含Root)。

Dim time = xmlDoc.Root.<Cube>.<Cube>[email protected] 
+0

如果你使用'XDocument'您需要先訪問'Root'屬性(我不知道'Load'將沒有一個XML申報工作在樣品上)。 OTOH你可以使用'XElement'而不是 – Sehnsucht

+0

謝謝@Sehnsucht我已經添加了失蹤的Root。我使用XElement開發它,然後被抓住了快捷方式。 – FloatingKiwi