I have xml file which I am trying to parse:
This is the xml file content
Your XML file doesn't load correctly.
a) I suppose your XML file starts with something like , so that it can be identified as XML.
b) It's preferable to declare your object settings (always use Option Explicit
in the declaration head). As you are using so called late binding, it's sufficient to write as follows:
Dim XDoc As Object
Dim lists As Object
Dim listNode As Object
Dim fieldNode As Object
Hint If you set your XDoc object to memory with Set XDoc = CreateObject("MSXML2.DOMDocument")
generally you are getting an older Version (3.0), so in most cases it's preferrable to use explicitly Set XDoc = CreateObject("MSXML2.DOMDocument.6.0")
instead, which includes XPath automatically. If not you should complete your code as follows:
Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False: XDoc.validateOnParse = False
XDoc.setProperty "SelectionLanguage", "XPath" ' << XPath functionality
c) Your XML file isn't loaded successfully because it contains a non readable character called ampersand ("&") within P Griffiths & Sons and Jo & hn, which has to be changed to "&
". The ampersand character is used as general prefix for special characters, so you can't be contained alone in the file. You can test loading with the following code instead of simply using XDoc.Load (ThisWorkbook.Path & "\test.xml")
:
If XDoc.Load(ThisWorkbook.Path & "\test.xml") Then
MsgBox "Loaded successfully"
Else
Dim xPE As Object ' Set xPE = CreateObject("MSXML2.IXMLDOMParseError")
Dim strErrText As String
Set xPE = XDoc.parseError
With xPE
strErrText = "Load error " & .ErrorCode & " xml file " & vbCrLf & _
Replace(.URL, "file:///", "") & vbCrLf & vbCrLf & _
xPE.reason & _
"Source Text: " & .srcText & vbCrLf & vbCrLf & _
"Line No.: " & .Line & vbCrLf & _
"Line Pos.: " & .linepos & vbCrLf & _
"File Pos.: " & .filepos & vbCrLf & vbCrLf
End With
MsgBox strErrText, vbExclamation
Set xPE = Nothing
Exit Sub
End If
d) BTW, there are other and more complete ways to loop through your nodes (recursive calls). Sure you'll find some at the SO site.