繁体   English   中英

如何使用VB.NET从XML获取属性值?

[英]How to get attribute value from XML using 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

我正在使用以下代码从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                                                                        

一种替代方法是使用VB.NET的很棒的Linq-to-XML功能(Framework 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").@rate
Dim currencyJPY = cubes.Where(Function(x) x.currency = "JPY").@rate

(注意:我所有的VB代码示例均假定Option Strict和Option Infer处于活动状态)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM