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

时间:2016-06-22 14:44:38

标签: xml excel vba excel-vba

我有以下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没有返回任何内容。它只返回Nothing

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

这有什么不对或我需要采取不同的方法吗?

1 个答案:

答案 0 :(得分:2)

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

sizeof...