我正在尝试使用 VBA 宏来解析 XML 文件。给出以下结构:
<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
如何使用元素标签及其对应值枚举输出,如下所示?book | category | children
title | harry potter
author | J K. Rowling
...
我的代码如下:Set xmlFile = CreateObject("Microsoft.XMLDOM")
xmlFile.Load (file)
Set qXML = xmlFile.SelectNodes("/bookstore")
For i = 0 To qXML.Length - 1
Debug.Print CStr(qXML(i).Text)
Next i
最佳答案
如何获取标签名称
"What's the XPath syntax to get Tag Names?"
严格来说是 (XML)DOM 获取
.Name
的语法和/或 .NodeName
特性;XMLDOM(文档对象模型)是一个跨平台且独立于语言的接口(interface),将文档视为树结构并允许对树进行编程访问。
但是,您可以使用 的特殊语法。 XPath 表达式(例如
"/bookstore/book/title"
)来处理分层 xml 文档结构中的任何逻辑部分。因此,接近您的 OP 的解决方案是:
Option Explicit ' declaration head of your code module
Sub ExampleCall()
Dim file As String: file = ThisWorkbook.Path & "\xml\bookstore.xml"
Dim xmlFile As Object
Set xmlFile = CreateObject("Microsoft.XMLDOM")
If xmlFile.Load(file) Then
Dim qXML As Object
Set qXML = xmlFile.DocumentElement.SelectNodes("book")
Dim q As Object
For Each q In qXML
Dim cnt As Long: cnt = cnt + 1
Debug.Print Format(cnt, "--- 000 ---")
Debug.Print q.Attributes(0).Name, "|" & q.Attributes(0).Text
Dim i As Long
For i = 0 To q.ChildNodes.Length - 1
Debug.Print q.ChildNodes(i).nodeName, "|" & q.ChildNodes(i).Text
Next
Next
End If
End Sub
结果在 VBE 的即时窗口 --- 01 ---
category |children
title |Harry Potter
author |J K. Rowling
year |2005
price |29.99
--- 02 ---
category |web
title |Learning XML
author |Erik T. Ray
year |2003
price |39.95
旁注如
Microsoft.XMLDOM
已被弃用多年,我更喜欢绑定(bind)到 ►
MSXML2
在最新的 xml 版本中 Microsoft XML,v6.0
,例如通过I. LATE Binding(如 OP)
Dim xDoc As Object
Set xDoc = CreateObject("MSXML2.DOMDocument.6.0")
二、早期绑定(bind) Dim xDoc As MSXML2.DOMDocument60 ' *) whereas MSXML2.DOMDocument (=old version 3.0)
Set xDoc = New MSXML2.DOMDocument60 ' mind the missing point in digits
旁注:OP 使用对象变量 XMLFile
而不是 xDoc
请注意,引用 DOMDocument
如果没有明显的版本控制,默认情况下会在内部绑定(bind)到 3.0(6.0 之前的最后一个稳定版本,不推荐使用任何其他版本)。
更多链接
关于excel - VBA - 获取标签名称的 XPath 语法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65284905/