Wednesday, 19 June 2013

XML File Parsing

XML File Parsing - Generic - VB code

Objective : Parse the XML to get all the nodes of any XML file .

First get the root node of the XML using oXml.documentElement.
Then check whether that root node has child nodes and do it repeatedly for all the nodes until its the last node.
The above can be achieved easily using recursion.

Belwo code can be used to parse any XML - To get all the nodes of XML

PS: The code is in VB but the same approach can be used for other languages and can be customized.


' Declare the variables
Dim oXml As DOMDocument
Dim oRoot As IXMLDOMNode
Dim Childnode As IXMLDOMNode

Sub ParseXml()

'Load the xml File
 Set oXml = CreateObject("Msxml2.DOMDocument")
 oXml.async = True
 xmlFile = ReadXMLfile(AnyFileLocation)
 oXml.loadXML xmlFile

'Set the root of the XML
Set oRoot = oXml.documentElement

'Call Recursive function and pass the root node of the XML
Call getChildNodes(oRoot)

End Sub

'Recursive function
Function getChildNodes(curNode As IXMLDOMNode)

'Çheck if the node has child nodes
If curNode.hasChildNodes = True Then
   For Each Childnode In curNode.childNodes
    'If yes then again call the recursive function

   Call getChildNodes(Childnode)

   'If not then its doesnt have any more child nodes and we can print the node
   MsgBox curNode.nodeName

End Function

No comments:

Post a Comment