gpt4 book ai didi

xml - 使用 VBA 将 XML 数据导入 Excel,selectnodes 不起作用(不返回任何内容)

转载 作者:行者123 更新时间:2023-12-02 13:56:14 25 4
gpt4 key购买 nike

我有以下 XML

<cqresponse xmlns="http://ibm.com/rational/cqweb/v7.1">
<rows>
<row>
<id>
<![CDATA[ ABC00082474 ]]>
</id>
<Short_Desc>
<![CDATA[
Some Description 1
]]>
</Short_Desc>
<State>
<![CDATA[ Some State 1 ]]>
</State>
</row>
<row>
<id>
<![CDATA[ ABC00082475 ]]>
</id>
<Short_Desc>
<![CDATA[
Some Description 2
]]>
</Short_Desc>
<State>
<![CDATA[ Some State 2 ]]>
</State>
</row>
</rows>
</cqresponse>

我想使用 VB 脚本将其导入 Excel。我有以下代码,但 SelectNodes 没有返回任何内容。它只是返回任何内容

Sub Test()
Dim nodeList As IXMLDOMNodeList
Dim nodeRow As IXMLDOMNode
Dim nodeCell As IXMLDOMNode
Dim rowCount As Integer
Dim cellCount As Integer
Dim rowRange As Range
Dim cellRange As Range
Dim sheet As Worksheet
Dim xpathToExtractRow As String
Dim dom As DOMDocument60

xpathToExtractRow = "/cqresponse/rows/row"

Set dom = New DOMDocument60
dom.Load ("C:\ABC.xml") ' this file contains the same xml data as mentioned above
Set sheet = ActiveSheet
Set nodeList = dom.SelectNodes(xpathToExtractRow)

rowCount = 0
For Each nodeRow In nodeList
rowCount = rowCount + 1
cellCount = 0
For Each nodeCell In nodeRow.ChildNodes
cellCount = cellCount + 1
Set cellRange = sheet.Cells(rowCount, cellCount)
cellRange.Value = nodeCell.Text
Next nodeCell
Next nodeRow
End Sub

这有什么问题吗?还是我需要采取不同的方法?

最佳答案

XML 解析中经常犯的错误是根中未声明的命名空间。因此,您必须在解析文档期间分配命名空间前缀,并在 XPath 表达式中使用此类前缀。下面,分配了doc:

...
Dim xpathToExtractRow As String, XMLNamespaces As String
Dim dom As DOMDocument60

xpathToExtractRow = "/doc:cqresponse/doc:rows/doc:row"
XMLNamespaces = "xmlns:doc='http://ibm.com/rational/cqweb/v7.1'"

Set dom = New DOMDocument60
dom.Load ("C:\ABC.xml")
dom.setProperty "SelectionNamespaces", XMLNamespaces
...

关于xml - 使用 VBA 将 XML 数据导入 Excel,selectnodes 不起作用(不返回任何内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37971408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com