2016-09-14 82 views
1

我有以下XML:如何使用VB.NET從XML獲取屬性值?

<?xml version="1.0" encoding="UTF-8"?> 
    <gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> 
    <gesmes:subject>Reference rates</gesmes:subject> 
    <gesmes:Sender> 
    <gesmes:name>European Central Bank</gesmes:name> 
    </gesmes:Sender> 
    <Cube> 
    <Cube time='2016-09-12'> 
     <Cube currency='USD' rate='1.1226'/> 
     <Cube currency='JPY' rate='114.38'/> 
    </Cube> 
    </Cube> 
    </gesmes:Envelope> 

我想每個屬性的貨幣價值。 現在我用的這個,但它不工作:

Dim xmlTree1 As New XmlDocument() 
    xmlTree1.Load("C:\\download\eurofxref-daily.xml") 

    Dim currencyUSD As String = xmlTree1.SelectSingleNode("/gesmes:Envelope/Cube/Cube/Cube[@currency='USD']/@rate").Value 
    Dim currencyJPY As String = xmlTree1.SelectSingleNode("/gesmes:Envelope/Cube/Cube/Cube[@currency='JPY']/@rate").Value 
+0

請將您嘗試從中提取的xml以及您創建xmlTree1的代碼發佈。 – FloatingKiwi

+0

我已經把XML和代碼的代碼放在了我創建xmlTree1的地方。 – SeaSide

+2

'gesmes'前綴需要註冊到命名空間。看到這篇關於使用命名空間管理器的文章https://support.microsoft.com/en-us/kb/318545 – FloatingKiwi

回答

1

另一種方法是使用VB.NET的真棒LINQ到XML功能(框架3.5及更高版本):

Imports <xmsns:xref="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> 

... 

Dim xdoc = XDocument.Load("C:\kursna_standalone\download\eurofxref-daily.xml") 
Dim cubes = xdoc.Root.<xref:Cube>.<xref:Cube> 
Dim currencyUSD = cubes.Where(Function(x) x.currency = "USD")[email protected] 
Dim currencyJPY = cubes.Where(Function(x) x.currency = "JPY")[email protected] 

(注:我所有的VB代碼示例假設選項嚴格和Option推斷是活動的)。

+0

謝謝你的回答Heinzi。這將與NET.Framework 4一起工作,但目前我正在使用NET.Framework 2並且它不識別XDocument。 – SeaSide

+0

@SeaSide:如果這是您的選擇,.NET Framework 3.5也應該可以正常工作。 – Heinzi

+0

這是很好的知道,因爲我一定會升級更新。謝謝。 – SeaSide

1

我使用下面的代碼從XML的價值和它的工作原理:

Dim xmlTree1 As New XmlDocument() 
xmlTree1.Load("C:\\kursna_standalone\download\eurofxref-daily.xml") 

Dim xmlnsManager1 As New System.Xml.XmlNamespaceManager(xmlTree1.NameTable) 
xmlnsManager1.AddNamespace("gm1", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref") 

Dim currencyUSD As String = xmlTree1.SelectSingleNode("//gm1:Cube/gm1:Cube/gm1:Cube[@currency='USD']/@rate", xmlnsManager1).Value 
Dim currencyJPY As String = xmlTree1.SelectSingleNode("//gm1:Cube/gm1:Cube/gm1:Cube[@currency='JPY']/@rate", xmlnsManager1).Value