首页 > 解决方案 > 在 Excel 中使用 Xpath 读取子节点的属性

问题描述

我在从 source_lvl2 子节点获取“数据导入”的值时遇到问题。在 Excel 中,我收到 91 的运行时错误,“对象变量或未设置块变量”

我看不出我做错了什么——有什么建议吗?

VBA

Sub TestXML()
Dim XDoc As Object

Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
XDoc.Load ("C:\171215-000438_1513346972.xml")

Set lists = XDoc.SelectNodes("/archive/primary_rnw_contact/source/source_lvl2")
Debug.Print lists(0).Attributes(0).Text
Set XDoc = Nothing
End Sub

XML

在此处输入图像描述

额外代码

<?xml version="1.1" encoding="UTF-8"?>
<archive product="RightNow" version="4.0" build="17.8.0.1.0.248" label="Archived Incident">

标签: excelvbaxpath

解决方案


您可以尝试以下(未测试):

Dim xmap As XmlMap
Dim k as Long
Dim oMyNewColumn As ListColumn
oMyList As ListObject

' Delete all previous XML maps
k = ThisWorkbook.XmlMaps.Count 'Detect all XML maps

For i = 1 To k
        ThisWorkbook.XmlMaps(i).Delete
Next i

...


Set xmap = ThisWorkbook.XmlMaps.Add("some_file.xml")

...

Set oMyNewColumn = oMyList.ListColumns.Add
    oMyList.ListColumns(3).XPath.SetValue xmap, "/archive/primary_rnw_contact/source/source_lvl2"

推荐阅读