在Excel中使用Xpath读取子节点的属性

时间:2019-04-02 10:26:32

标签: excel vba xpath

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

我看不到我在做什么错-有任何建议吗?

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

enter image description here

其他代码

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

1 个答案:

答案 0 :(得分:0)

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

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"