Thursday, October 11, 2012

How to read XML files using vb6.0

RAM RAM Friends


After a very very long time, I got very few moments to share my knowledge.

Here is how we can read, write etc from/to XML files using vb6.0


Step 1 >> Set Reference to "Microsoft XML, v2.6" as below

Project Menu>References>select "Microsoft XML, v2.6">OK

Step 2 >> Have any one XML file to read data from it.

  Below is the sample file I Used in this sample program

test.xml

<check> 
    <header>
         <outlet> AK </outlet>
         <profilename> ARUN KAKKAR </profilename>
    </header>
   <item>
           <code> C1 </code>
          <name> ITEM 1 </name>
          <qty> 2 </qty>
   </item>
   <item>
          <code> C2 </code>
          <name> ITEM 2 </name>
          <qty> 5 </qty>
   </item>

</check>


Step 3 >  Make procedure to read the file

  • Private sub ParseXMLDoc_ak()
    • Dim doc as new MSXML2.DOMDocument
    • Dim bsuccess as boolean, s as string , s2 as string
    • bsuccess=doc.Load(App.Path & "\ test.xml")
    • if bsuccess=false then
      • msgbox doc.parseError.reason
      • exit sub
    • end if
    • Dim n1 as MSXML2.IXMLDOMNode
    • Dim n2 as MSXML2.IXMLDOMNode
    • Dim n3 as MSXML2.IXMLDOMNode
    • Dim i as Integer 
    • s="SrNo    Code    Name         Qty"
    • For Each n1 in doc.childNodes
      • 'n1=RootNode eg. CHECK
      • For Each n2 In n1.childNodes
        • 'n2=1st Level child node i.e. child of n1 , e.g. ITEM, HEADER
          • If UCase(n2.nodeName)="ITEM" or UCase(n2.nodeName)="HEADER" Then
            • For Each n3 in n2.childNodes
              • 'n3=2nd Level child Node i.e. child of n2 e.g. OUTLET,  
              • '  PROFILENAME,CODE, QTY, NAME
              • Select Case UCase(n3.nodeName)
                • Case "OUTLET"
                  • s2=s2 &  vbcrlf & "Outlet=" & n3.Text
                • Case "PROFILENAME"
                  • s2=s2 & "  " & "Profile Name=" & n3.Text
                • Case "CODE"
                  • i=i+1     
                  • s=s & vbcrlf & i & " " & n3.Text
                • Case "NAME"
                  • s=s & "  " & n3.Text
                • Case "QTY"
                  • s=s & "  " & val(n3.Text)
              • End Select
            • Next n3
          • End if 
        • Next n2
      • Next n1
      • if s <>; "" then MsgBox s2 & vbcrlf & s
    • End Sub     

Step 4 > Below would be the output of above code

Outlet= AK      Profile Name=ARUN KAKKAR
SrNo      Code       Name      Qty
1     C1        ITEM 1       2
2     C2        ITEM 2       5   

Note:
1. The above code is just very minimal use of the various features provided by "MSXML2 OBJECT"
2. You can use other methods &amp; properties of this object to make it very easier to use xml in vb6.0

I hope, it would help you in dealing with XML files in much more better way,