xml - DOM + XML 问题 + 到底发生了什么?

标签 xml vba dom

我对 XML 和 DOM 还很陌生。我正在尝试从 http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml 获取美元汇率

代码现在运行得很好,但我并没有真正理解正在发生的事情的几个部分。

问题

  • 在 XML 文件中,我看到几个“xmlns”标签,我知道这些标签用于命名空间,但我从未遇到过有两个标签的情况。当我创建命名空间引用时,为什么它是我使用的最后一个命名空间?

  • 当我选择节点时,我认为要访问多维数据集节点,我应该使用 xDOM.selectNodes("/f:gesmes/f:gesmes/f:Cube") 但是这个和任何其他f:gesmes 的组合返回零(!)个节点。我能够访问多维数据集节点的唯一方法是通过//表达式

  • 为什么如果没有错误处理过程,代码就无法工作?如果没有 On Error Resume Next,代码会抛出“对象变量或未设置 block ”错误

我的代码

Option Explicit

Private Sub run() ' run the whole operation'

Dim http_req As http_req: Set http_req = New http_req
Dim xDom As MSXML2.DOMDocument60
Set xDom = New MSXML2.DOMDocument60

Dim url As String: url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
xDom.async = False
xDom.Load url

Do Until xDom.ReadyState = READYSTATE_COMPLETE
    DoEvents
Loop

Call find_ClassElement(xDom)

End Sub

Private Sub find_ClassElement(xDom As MSXML2.DOMDocument60)

Dim ticker As String
Dim if_USD As String

Dim xDOM_element As MSXML2.IXMLDOMElement
Dim xDOM_attribute As MSXML2.IXMLDOMAttribute
Dim xDom_selection As MSXML2.IXMLDOMSelection
Dim xDOM_nodeList As MSXML2.IXMLDOMNodeList

xDom.setProperty "SelectionNamespaces", "xmlns:f='http://www.ecb.int/vocabulary/2002-08-01/eurofxref'"

Set xDOM_nodeList = xDom.SelectNodes("//f:Cube")

For Each xDOM_element In xDOM_nodeList
        On Error Resume Next
        if_USD = xDOM_element.Attributes(0).text
        On Error GoTo 0
        If if_USD = "USD" Then
            ticker = xDOM_element.Attributes(1).text
        End If
        Next
    Debug.Print ticker
End Sub

最佳答案

关于问题 #1,拥有多个命名空间并没有什么特别之处,许多 XML 都有它。没有前缀的命名空间 ( xmlns="...." ) 被识别为默认命名空间。基本上都有默认命名空间,所有后代节点和声明默认命名空间的节点都继承相同的命名空间。除非节点显式使用指向不同命名空间 URI 的前缀,或者在本地声明了不同的默认命名空间。

这就是为什么您需要注册f的原因前缀并将其用于 <Cube>尽管 <Cube> 的节点s 没有前缀或命名空间声明它们自身(因为它们从父节点 <gesmes:Envelope> 继承默认命名空间。并且它自身的 Envelope 节点不在默认命名空间中,因为它有 gesmes 前缀)。 p>

关于问题#2,如果仔细查看 XML,您会发现最内部 <Cube> 的正确路径节点如下:

/gesmes:Envelope/f:Cube/f:Cube/f:Cube

..您可能需要注册gesmes在 XPath 中使用 namespace 前缀(以及 f 前缀)之前。

关于问题 #3,您可以使用纯 XPath 表达式以更干净、更安全的方式获取美元汇率:

//f:Cube[@currency='USD']

这个 XPath 告诉只返回 <Cube>具有 currency 的节点属性值等于USD .

关于xml - DOM + XML 问题 + 到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26005788/

相关文章:

vba - For Each 在 Excel VBA 中不起作用

javascript - DOM指定属性返回true

javascript - DOM 循环中的 HTML5 Canvas

XML文件和&字符?

android - 颜色.xml : Error: Unsupported type 'component' (Android studio)

java - 如何将 XML 文件中的 x 和 y 坐标解析为 Java 中的 Point2D 数组?

Java错误: Unable to initialize main class

vba - Excel - 使用格式(日期)写入文本文件

Excel VBA 自动筛选值不等于 Asterisk (*)

php - Wordpress 网站中的 fatal error : Class 'DOMDocument' not found,