2016-09-14 18 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

私はxmlTree1を作成する場所にXMLとコードのコードを入れました。 – SeaSide

+2

'gesmes'接頭辞は名前空間に登録する必要があります。名前空間マネージャの使用に関するこの記事を参照してください。https://support.microsoft.com/en-us/kb/318545 – FloatingKiwi

答えて

1

代替が使用する今、私はこれを使用していますが、それは動作しませんのために VB.NET(フレームワーク3.5以上)の素晴らしいLINQのツーXML機能:

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                   
関連する問題