Parse XML from VBA not working

谁说胖子不能爱 提交于 2021-02-07 10:30:39

问题


I am trying to parse xml file using excel vba. This is how my xml file looks like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Environment>
    <Variable>
        <Name></Name>
        <Caption>T1</Caption>
        <Type>TEXT</Type>
        <Value>V1</Value>
        <Description></Description>
    </Variable>
        <Variable>
        <Name></Name>
        <Caption>T2</Caption>
        <Type>TEXT</Type>
        <Value>V2</Value>
        <Description></Description>
    </Variable>
        <Variable>
        <Name></Name>
        <Caption>T3</Caption>
        <Type>TEXT</Type>
        <Value>V3</Value>
        <Description></Description>
    </Variable> <Variable>
        <Name></Name>
        <Caption>T4</Caption>
        <Type>TEXT</Type>
        <Value>V4</Value>
        <Description></Description>
    </Variable> <Variable>
        <Name></Name>
        <Caption>T5</Caption>
        <Type>TEXT</Type>
        <Value>V5</Value>
        <Description></Description>
    </Variable>
    </Variable> <Variable>
        <Name></Name>
        <Caption>T6</Caption>
        <Type>TEXT</Type>
        <Value>V6</Value>
        <Description></Description>
    </Variable>
</Environment>

And here is my code to parse it:

Public Function ll()
Dim doc As DOMDocument60
Set doc = New DOMDocument60
doc.Load "E:\web\cc.xml"
Dim Variables As IXMLDOMNodeList
Dim variable As IXMLDOMNode
Set Variables = doc.SelectNodes("/Environment/Variable")
For Each variable In Variables
    Debug.Print variable.SelectNodes("Caption").Item(0).Text
    Debug.Print variable.SelectNodes("Type").Item(0).Text
Next
End Function

But I am not able to get this successfully run. I am using Excel 2013 and I have referenced to Microsoft XML 6.0. But nothing happens on execution. I tried to catch error with an on error statement, but it returns error number 0. Can anybody tel what I am doing wrong here.


回答1:


A XML parser can only work if the XML is well formed. If not, the oXMLDOMDocument.load method fails.

To check this, you could use oXMLDOMDocument.parseError like this:

Public Function ll()

 Dim oDoc As Object
 Set oDoc = CreateObject("MSXML2.DOMDocument")
 oDoc.Load "E:\web\cc.xml"

 Dim oErr As Object

 If oDoc.parseError.ErrorCode <> 0 Then
  Set oErr = oDoc.parseError
  Debug.Print oErr.reason
 End If

 Dim oVariables As Object
 Dim oVariable As Object
 Set oVariables = oDoc.SelectNodes("/Environment/Variable")
 For Each oVariable In oVariables
  Debug.Print oVariable.SelectNodes("Caption").Item(0).Text
  Debug.Print oVariable.SelectNodes("Type").Item(0).Text
 Next

End Function

See: https://msdn.microsoft.com/en-us/library/ms762722%28v=vs.85%29.aspx



来源:https://stackoverflow.com/questions/30748689/parse-xml-from-vba-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!